What is the difference between "Parent c = new Child()" and "Child c = new Child()"?
I am new to Java so please bear with me, I tried looking this question up but I’m having trouble since I don’t know the underlying terms involved in this question.
Assuming:
class Parent {} class Child extends Parent {}
What is the difference between:
Parent c = new Child();
and
Child c = new Child();
Thanks in advance for any help you can provide.
At runtime there is no difference.
There is a difference only for the Java compiler (and type checker). In the first case you are declaring that the most informative thing that you know about the c
is that it is a Parent
, even if the runtime type is more specific.
This has two main effects:
c
can be used when aParent
is needed but not when aChild
is needed- if you want to change the type of
c
to another type (let’s supposeclass Nephew extends Parent
) the only necessary thing is to change the instantiation (eg.new Child()
becomesnew Nephew()
The second effect is a consequence of the fact that, if the code compiles and c
is declared as a Parent
, this implies that you are not using any feature which is not already declared in Parent
, so every other class which extends from Parent
is a valid substitute.
remember this in java- a parent class object can hold the reference to a child class object..
this is exactly what is being done here.
plus look at this Does Parent obj = new Child(); make sense?