Which Overloaded Method is Called in Java
I have a basic inheritance situation with an overloaded method in the super class.
public class Person {
private String name;
private int dob;
private String gender;
public Person(String theName, int birth, String sex){
name = theName;
dob = birth;
gender = sex;
}
public void work(){
getWorkDetail(this);
}
public void getWorkDetail(Employee e){
System.out.println("This person is an Employee");
}
public void getWorkDetail(Person p){
System.out.println("This person is not an Employee");
}
}
The following class extends the class above:Employee
Person
public class Employee extends Person {
String department;
double salary;
public Employee(String theName, int birth, String sex){
super(theName, birth, sex);
department = "Not assigned";
salary = 30000;
}
}
The main method simply creates an object (both static and dynamic type) and calls on it:Employee
.work()
public static void main(String[] args){
Employee e1 = new Employee("Manager1", 1976, "Female");
e1.work();
}
This ends up printing
This person is not an Employee
Looking through this I had thought that since both the static and dynamic type of the object is it would call the overloaded method in Person that takes an as a parameter. Since I am clearly wrong about this I opened a debugger assuming the reference to "this" at the line in the class must have morphed to it's super class. However this is not what I found.e1
Employee
Employee
getWorkDetail(this)
Person
Clearly at this point in the code is an object, however it still chose to execute the overloaded method . Can anyone explain this behavior?this
Employee
getWorkDetail(Person p)