First, clarification of the terminology: we assign the Child object to a variable of type Parent . Parent is a reference to an object that is a subtype of Parent , a Child .
This is only useful in a more complex example. Imagine that you add getEmployeeDetails to the Parent class:
public String getEmployeeDetails() { return "Name: " + name; }
We could override this method in Child to provide more details:
@Override public String getEmployeeDetails() { return "Name: " + name + " Salary: " + salary; }
Now you can write one line of code that receives any information, whether it be a Parent or Child object:
parent.getEmployeeDetails();
The following code:
Parent parent = new Parent(); parent.name = 1; Child child = new Child(); child.name = 2; child.salary = 2000; Parent[] employees = new Parent[] { parent, child }; for (Parent employee : employees) { employee.getEmployeeDetails(); }
Result:
Name: 1 Name: 2 Salary: 2000
We used Child as Parent . It had specialized behavior unique to the Child class, but when we called getEmployeeDetails() , we could ignore the difference and focus on how Parent and Child are similar. This is called a subtype of polymorphism .
The updated question asks why Child.salary not available if the Child object is stored in the Parent link. The answer is the intersection of "polymorphism" and "static typing." Since Java is statically typed at compile time, you get certain guarantees from the compiler, but you have to follow the rules in exchange or the code will not compile. An appropriate guarantee here is that each instance of a subtype (e.g. Child ) can be used as an instance of its supertype (e.g. Parent ). For example, you are guaranteed that when accessing employee.getEmployeeDetails or employee.name method or field is defined for any non-empty object that can be assigned to an employee variable of type Parent . To make this guarantee, the compiler only considers this static type (mainly the variable reference type, Parent ) when deciding what you can access. Therefore, you cannot access elements defined in the runtime type, Child .
If you really want to use Child as Parent , this is a simple limitation on life, and your code will be used for Parent and all its subtypes. If this is not acceptable, enter the link type Child .