Call a child class method from a parent class object

后端 未结 7 543
星月不相逢
星月不相逢 2020-12-06 09:35

I have the following classes

class Person {
    private String name;
    void getName(){...}}

class Student extends Person{
    String class;
    void getCl         


        
7条回答
  •  情深已故
    2020-12-06 10:17

    NOTE: Though this is possible, it is not at all recommended as it kind of destroys the reason for inheritance. The best way would be to restructure your application design so that there are NO parent to child dependencies. A parent should not ever need to know its children or their capabilities.

    However.. you should be able to do it like:

    void calculate(Person p) {
        ((Student)p).method();
    }
    

    a safe way would be:

    void calculate(Person p) {
        if(p instanceof Student) ((Student)p).method();
    }
    

提交回复
热议问题