javaoopclass-designinstanceof

Calling method that exists in child classes but not in parent class


public class Parent {
    ....
}

public class Child1 extends Parent {
    ....
    public void foo() {
        ....
    }
}

public class Child2 extends Parent {
    ....
    public void foo() {
        ....
    }
}

Here method foo() only exists in the Child classes and can not be added to the Parent class (not even abstract method). In this situation, when I want to call the foo() method on obj which is Parent class's reference, then I need to use intanceof with multiple if..else, that I want to avoid.

Parent obj = ...// Object of one of the child classes
obj.foo();

EDIT: I need to use type of obj as Parent only. Otherwise, I will not be able to call methods on obj which exists in Parent class.


My Solution: The approach that I am thinking is to define an interface to say FooInterface with foo() method and let all the child classes implement it, then I could just type cast the obj to that interface and call foo() method like this:

if(obj instanceof FooInterface){
    ((FooInterface)obj).foo();
}

Is there a better approach? Or any improvement to this one?


Solution

  • The approach that I am finally taking is to define an interface say FooInterface with foo() method and let all the child classes implement it, then I could just type cast the obj to that interface and call foo() method like this:

    Parent obj = ...// Object of one of the child classes
    .....
    if(obj instanceof FooInterface){
        ((FooInterface)obj).foo();
    }