首页 > 解决方案 > Java调用继承的方法只使用一个对象

问题描述

如何仅使用任何一个类的对象调用 2 个类(继承)的方法。
考虑代码

class Employee
{
    void display()
    {
        System.out.println("Name of class is Employee");
    }

    void calcSalary()
    {
        System.out.println("Salary of employee is 10000");
    }
}

class Engineer extends Employee
{
    void display()
    {
        System.out.println("Name of class is Engineer");
    }
    void calcSalary()
    {
        System.out.println("Salary of engineer is 20000");
    }
}

如果我将一个对象声明为

Employee ob = new Employee();
ob.display();  //prints "Name of class is Employee"
ob.calcSalary(); //prints "Salary of employee is 10000"

相似地

Engineer ob = new Engineer();
ob.display();  //prints "Name of class is Engineer"
ob.calcSalary();  //prints "Salary of engineer is 20000"

如何仅使用单个实例(任一类)获得所有这 4 个输出?

标签: java

解决方案


通过添加super.display()inhereted 方法的第一行,您可以调用父类的方法。


推荐阅读