public class Parent {
....
}
public class Child1 extends Parent {
....
public void foo() {
....
}
}
public class Child2 extends Parent {
....
public void foo() {
....
}
}
Here, the method foo()exists only in Child classes and cannot be added to the Parent class (even an abstract method). In this situation, when I want to call a method foo()on objwhich is a reference Parent, then I need to use intanceofwith a few if..elsethat I want to avoid.
Parent obj = ...
obj.foo();
EDIT: I need to use the type objonly as Parent. Else I will not call methods on obj, which exists in the parent class.
: , , , , FooInterface foo() , cast obj foo() :
if(obj instanceof FooInterface){
((FooInterface)obj).foo();
}
? ?