0

I am currently learning Java as a past time, and I am troubling in absorbing this instantiation syntax. I know that if a Main class is created, I can create an object by using this

Main obj = new Main();

But in further lectures (specifically inheritance and polymorphism), they are creating objects as

Parentclass object = new Subclass();

I've tried using

Subclass object = new Subclass();

and have the same output.

Can you please tell me the difference about these two?

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Dan R.
  • 1
  • 2
    The difference is that if the variable `object` is defined as a `Parentclass` you can assign `Subclass` or `Parentclass` or `OtherSubclass` instances to it. It also means that you can only access the instance through the `Parentclass` interface, so if `Subclass` exposes additional methods they won't be callable. – jonrsharpe Feb 23 '22 at 10:47
  • Thank you very much @jonrsharpe. This is troubling me in the past lectures and I might miss something about this two syntaxes. thank you very much. – Dan R. Feb 23 '22 at 10:55
  • Also [Why do we assign a parent reference to the child object in Java?](https://stackoverflow.com/questions/12159601/why-do-we-assign-a-parent-reference-to-the-child-object-in-java?rq=1) – Federico klez Culloca Feb 23 '22 at 10:57

0 Answers0