Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance and polymorphism - understanding

I have a class A and class B which extends A and is a subclass. Now i have

A aObject = new A(); and
A bObject = new B();

Now can i call the method in class B which is not in A using bObject without typecasting ?

If we cant do so without typecasting, what is the advantage of polymorphism then?

Thanks.

like image 740
nik7 Avatar asked Nov 27 '25 17:11

nik7


2 Answers

No, you definitely need to cast bObject to B.

This is because, as far as the compiler is concerned, bObject is of the declared class A. Imagine that instead of using a constructor, you had returned bObject from a function which returns class A..... how could the compiler possibly know that it is actually of class B?

You therefore need to do a runtime cast or instanceof check before the compiler will let you use it as class B.

like image 154
mikera Avatar answered Nov 30 '25 07:11

mikera


No, you cannot. On both objects aObject and bObject you can call only methods that are defined for A without using casting.

If you defined bObject to be of type B, then you could, but as your code stands you can only work with A's methods and members.

like image 33
nicholas.hauschild Avatar answered Nov 30 '25 07:11

nicholas.hauschild



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!