多态性——调用基类函数
是否可以在不修改基类和派生类的情况下调用基类函数?
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());
}
}
输出: 员工 1000 6000
我该如何调用 em
对象上的 Employee 的 getSalary() 方法?
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
How shall I call the Employee's getSalary() method on em
object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你不能。如果需要,您可以向
Manager
添加这样的方法:You can't. You could add a method like this to
Manager
if you wanted:使用 Employee 对象代替:
Use an Employee object instead:
您可以从子类中调用超类的方法。
You can call the superclass's method from within the subclass.