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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With