Call a child class method from a parent class object

后端 未结 7 555
星月不相逢
星月不相逢 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条回答
  •  猫巷女王i
    2020-12-06 10:16

    A parent class should not have knowledge of child classes. You can implement a method calculate() and override it in every subclass:

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

    and then

    class Student extends Person{
        String class;
        void getClass(){...}
    
        @Override
        void calculate() {
            // do something with a Student
        }
    }
    

    and

    class Teacher extends Person{
        String experience;
        void getExperience(){...}
    
        @Override
        void calculate() {
            // do something with a Student
        }
    
    }
    

    By the way. Your statement about abstract classes is confusing. You can call methods defined in an abstract class, but of course only of instances of subclasses.

    In your example you can make Person abstract and the use getName() on instanced of Student and Teacher.

提交回复
热议问题