如果在 Parent class 和 Child Class 中有两个同名的方法..?

if there are two methods with same name in Parent class and Child Class ..?

如果Parentclass和ChildClass中有两个同名的方法,例如:

Parent class:

public abstract class Employee implements Payments {
    private String name;
    protected double basicSalary;

    public Employee(String name, double basicSalary) {
        this.basicSalary = basicSalary;
        this.name = name;
    }

    public void display() {
        System.out.println( " Name: " + name + " - Basic Salary: " + basicSalary +"SR" );
    }
}

Child class:

public class Faculty extends Employee {
    private String degree;
    private int teachingHours;

    public Faculty(String name, double salary, String degree, int teachingHours) {
        super(name, salary);
        this.degree = degree;
        this.teachingHours = teachingHours;
    }   

    public void display() {
        System.out.println( " Name: " +getName() + " - Degree:" +degree);
    }

然后我创建了一个 object 这样的:

Employee[] arrEm = new Employee[4];
arrEm[0] = new Faculty("ahmad", 1000, "Phd", 10);

所以如果我写

arrEm[0].display();

这样 display() 方法将在 child 中使用。但是万一我们要使用ParentClass中的方法显示,怎么办呢?

提前致谢!

你必须这样称呼它:

super.display();

然后要么不要在子 class 中声明显示方法,要么创建父 class 的实例而不是子 class 的实例,例如 rrEm[0]= new Employee("ahmad" , 1000 )(虽然我没有认为你想要这个)或从子 class 调用父方法,如 super.display()

这是因为您首先要: Employee [] arrEm = new Employee [4]; 这将为对象创建 arrEm 数组。然后你这样做: arrEm[0]= new Faculty("ahmad" , 1000 , "Phd" , 10 ); 您使用 arrEm[0] 来引用子 class 对象,因此它将使用子对象的显示。这是多态性的正常情况。您可以在 google 上搜索它。这很有用。如果您想使用父显示,请使用

arrEm[0] = new Employee;

或者有一种方法像

child a= new child();

父级 p=(父级)a;

此 a.display() 将使用父 class 中的显示。

如果你想调用父class的display方法,你应该在Facultyclass的display()方法中添加super.dislay()。

public class Faculty extends Employee {
private String degree;
private int teachingHours;

public Faculty( String name , double salary , String degree , int teachingHours) 
{
    super(name , salary );
    this.degree=degree;
    this.teachingHours = teachingHours;
}   
public void display()
{
    //calling display() method of parent class
    Super.display();
    System.out.println( " Name: " +getName() + " - Degree:" +degree);
}

或 如果您不想从子 class 调用它,则使用父 class 构造函数而不是子 class.

创建对象
  Employee [] arrEm = new Employee [4];
  //calling parent class constructor
  arrEm[0]= new Employee("ahmad");

在这里你不能使用 Faculty class(degree, teachingHours) 的成员。