I am asking a quite simple question, but I am bit confused in this.
Suppose I have a class Parent:
public class Parent {
int name;
}
And have another class Child:
public class Child extends Parent{
int salary;
}
And finally my Main.java class
public class Main {
public static void main(String[] args)
{
Parent parent = new Child();
parent.name= "abcd";
}
}
If I make a child object like
Child child = new Child():
Then child object can access both name and salary variables.
My question is:
Parent parent = new Child();
gives the access of only name variable of Parent class.
So what is the exact use of this line??
Parent parent = new Child();
And also when it is using dynamic polymorphism then why the variable of child class is not accessible after doing this
Parent parent = new Child();
First, a clarification of terminology: we are assigning a
Childobject to a variable of typeParent.Parentis a reference to an object that happens to be a subtype ofParent, aChild.It is only useful in a more complicated example. Imagine you add
getEmployeeDetailsto the class Parent:We could override that method in
Childto provide more details:Now you can write one line of code that gets whatever details are available, whether the object is a
ParentorChild:The following code:
Will result in the output:
We used a
Childas aParent. It had specialized behavior unique to theChildclass, but when we calledgetEmployeeDetails()we could ignore the difference and focus on howParentandChildare similar. This is called subtype polymorphism.Your updated question asks why
Child.salaryis not accessible when theChildobject is stored in aParentreference. The answer is the intersection of “polymorphism” and “static typing”. Because Java is statically typed at compile time you get certain guarantees from the compiler but you are forced to follow rules in exchange or the code won’t compile. Here, the relevant guarantee is that every instance of a subtype (e.g.Child) can be used as an instance of its supertype (e.g.Parent). For instance, you are guaranteed that when you accessemployee.getEmployeeDetailsoremployee.namethe method or field is defined on any non-null object that could be assigned to a variableemployeeof typeParent. To make this guarantee, the compiler considers only that static type (basically, the type of the variable reference,Parent) when deciding what you can access. So you cannot access any members that are defined on the runtime type of the object,Child.When you truly want to use a
Childas aParentthis is an easy restriction to live with and your code will be usable forParentand all its subtypes. When that is not acceptable, make the type of the referenceChild.