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.
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();
}