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

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

    You can't do it with parent object reference until an unless method is declared in parent class/interface itself.

    You have to downcast it to child class because parent class/interface doesn't have any knowledge about the child class other than the contract defined between them.

    Here contract means abstract methods.


    you can try in this way where there is no need to put a check it.

    FooInterface sc =new Child1();
    sc.foo();
    
    ...
    
    interface FooInterface{
        void foo();
    }
    
    public class Parent {
    
    }
    
    public class Child1 extends Parent implements FooInterface{
    
        public void foo() {
    
        }
    }
    
    public class Child2 extends Parent implements FooInterface{
    
        public void foo() {
    
        }
    }
    

提交回复
热议问题