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

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

    If you want to typecast only then there is no need of adding interface. You can typecast it to your desired class and call the method. Example

    public class HelloWorld {
        public static void main(String args[]) throws FileNotFoundException {
            SuperClass sc =new Child1();
            if(sc instanceof Child1)//Do same for Child2
            ((Child1)sc).foo();
        }
    }
    
    class SuperClass {
    
    }
    
    class Child1 extends SuperClass{
        public void foo(){
            System.out.println("From child1");
        }
    }
    
    class Child2 extends SuperClass{
        public void foo(){
            System.out.println("From child2");
        }
    }
    

    Output : From child1

提交回复
热议问题