-1

Resources which teach Java seem to have conflicting answers on whether it's possible to both override a parent class's method and also create a new method from within a subclass at the same time. When I try the following:

class ABC{
     //Overridden Method
     public void disp(){
          System.out.println("disp() method of parent");
     }
}

class DEF extends ABC{
     //Overriding Method
     public void disp(){
          System.out.println("disp() method of child");
     }
     //new method in the subclass
     public void newMethod(){
          System.out.println("new method of child class");
     }
     public static void main(String args[]){
          ABC obj = new ABC();
          obj.disp();
          ABC obj2 = new DEF();
          obj2.disp();
          obj2.newMethod();
     }
}

java throws a "cannot find symbol" error. Is there something I'm missing? It seems strange that one couldn't do both at once and yet I can't seem to escape that error.

1
  • Are these classes defined in two separate files?
    – lucasvw
    Oct 1, 2019 at 20:59

2 Answers 2

6

If you have a reference to an object, where the variable is defined as ABC, then you can only call methods that are defined on the class ABC. Even if the underlying object is of type DEF, the variable itself is defined to hold an ABC.

Try changing your code from this:

ABC obj2 = new DEF();

to this:

DEF obj2 = new DEF();

It will work because you are defining obj2 to be of type DEF.

Here's another example showing creation of a string, first with a variable defined for type String, and another with type defined as Object.

String s = new String();
s.charAt(99);             <-- this is valid on a String

Object o = new String();
o.charAt(99);             <-- same thing, but not allowed on Object

A workaround would be to use instanceof to check if obj2 is actually an instance of DEF, and if so, temporarily use it like a DEF by casting it, like this:

if (obj2 instanceof DEF) {
    ((DEF) obj2).newMethod();
}
1
  • 1
    Fantastic, thank you!! I was hung up on this for a while!
    – Stanley
    Oct 2, 2019 at 21:11
3

Here ABC is the superclass and DEF is the subclass. So when you do ABC obj2 = new DEF(); , obj2 can access only those functions which are defined in ABC. As newMethod() is not defined in ABC, you can not call it using obj2.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.