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.

Add Comment
2 Answer(s)

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 a Parent is needed but not when a Child is needed
  • if you want to change the type of c to another type (let’s suppose class Nephew extends Parent) the only necessary thing is to change the instantiation (eg. new Child() becomes new 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.

Add Comment

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?

Answered on July 16, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.