I have question regarding polymorphism about its assignment statement, for Example this is The Super class
public class Person {
private String firstName;
private String middleInitial;
private String lastName;
private int age;
public Person(String firstName,String middleInitial , String lastName , int age){
setFirstName(firstName);
setMiddleInitial(middleInitial);
setLastName(lastName);
setAge(age);
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public String getFirstName(){
return firstName;
}
public void setMiddleInitial(String middleInitial){
this.middleInitial = middleInitial;
}
public String getMiddleInitial(){
return middleInitial;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public String getLastName(){
return lastName;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return age;
}
public String toString(){
return String.format("First Name: "+getFirstName()+"\nMiddle Initial: "+getMiddleInitial()+
"\nLast Name: "+getLastName()+"\nAge: "+getAge());
}
}
And this is The Derived Class
public class Employee extends Person{
private Contact contact;
public Employee(String firstName,String middleInitial , String lastName , int age, Contact contact){
super(firstName,middleInitial,lastName,age);
this.contact = contact;
}
public String toString(){
return String.format(super.toString()+contact.toString());
}
}
Now my question is what’s the Difference Between these assignment statements ?? and what are the difference ? I know Employee is a Person but I want to know what’s the difference between these two:
Person employee1 = new Employee();
Employee employee2 = new Employee();
and This
Employee employeeKyle = new Employee();
Person employeeKyel2 = employeeKyle;
I am kinda having a hard time about these .
In the first one you have 2 OBJECTS, both are of the type Employee, and you have 2 different references to them, one being a Person reference and the other being an Employee reference.
In the second case, you have 1 OBJECT with 2 REFERENCES pointing to it, being one a Person and another an Employee.
The object is always of the type you’ve instantiated it with the new keyword (in this case, the object is always an employee). You can, however, have different types of references pointing to the actual object (the references can be either of the type of the object or of one of its superclasses).