Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Base b = new Derived(); inheritance questions

What exactly happens when you create a new instance using :

Base b = new Derived();

I cannot really understand the mechanics behind this.

like image 666
Eternal_Light Avatar asked Aug 28 '11 17:08

Eternal_Light


2 Answers

The reference to b is type Base. But the implementation is Derived. This means you can use it as a Base but it will behave as a Derived. Doing b instanceof Derived will be true because the implementation is of type Derived

like image 105
Amir Raminfar Avatar answered Oct 22 '22 00:10

Amir Raminfar


Basically, from that point the compiler sees a Baseinstance and in runtime the instance is of type Derived.

In a broader explanation the Basetype might be a interface, so you know by the contract what method has and what it does Polymorphism. But you are abstracted from the implementation.

like image 23
ssedano Avatar answered Oct 21 '22 23:10

ssedano