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

后端 未结 5 2032
被撕碎了的回忆
被撕碎了的回忆 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:40

    You could implement an AbstractChild inheriting from Parent and then extend this class instead of Parent:

    public class Parent {
        ....
    }
    
    public abstract class AbstractChild extends Parent{
    
        public abstract void foo();
    
    }
    
    
    
    public class Child1 extends AbstractChild {
        ....
        public void foo() {
            ....
        }
    }
    
    public class Child2 extends AbstractChild {
        ....
        public void foo() {
            ....
        }
    }
    

    So you need to only check if your instance is instanceof AbstractChild.

提交回复
热议问题