简体   繁体   English

多态-调用基类函数

[英]Polymorphism - Call Base class function

Is it possible to call base class function without modifying both base and derived classes? 是否可以在不修改基类和派生类的情况下调用基类函数?

class Employee {
    public String getName() {
        return "Employee";
    }

    public int getSalary() {
        return 5000;
    }
}

class Manager extends Employee {
    public int getBonus() {
        return 1000;
    }

    public int getSalary() {
        return 6000;
    }
}

class Test {
    public static void main(String[] args) {
        Employee em = new Manager();
        System.out.println(em.getName());
        // System.out.println(em.getBonus());
        System.out.println(((Manager) em).getBonus());
        System.out.println(em.getSalary());
    }
}

Output: Employee 1000 6000 输出:员工1000 6000

How shall I call the Employee's getSalary() method on em object? 如何在em对象上调用Employee的getSalary()方法?

You can't. 你不能 You could add a method like this to Manager if you wanted: 您可以根据需要向Manager添加这样的方法:

public int getEmployeeSalary()
{
    return super.getSalary();
}

改用Employee对象:

Employee em = new Employee();

You can call the superclass's method from within the subclass. 您可以从子类中调用超类的方法。

class Manager extends Employee {
    public int getBonus() {
    return 1000;
    }

    public int getSalary() {
    return super.getSalary();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM