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

后端 未结 5 2041
被撕碎了的回忆
被撕碎了的回忆 2020-12-07 02:11
public class Parent {
    ....
}

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

public class Child2 extends Parent {
           


        
5条回答
  •  被撕碎了的回忆
    2020-12-07 02:43

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

提交回复
热议问题