My question is regarding Inheritance and Polymorphism.
I have a class A which is the super class. Classes B and C extends A and are subclasses.
Now i have a function in other class(not A or B or C) that takes argument of type A. So polymorphism allows us to pass the argument as A , B or C to that function. Now in that function, inorder to access B‘s properties, i have to typecast the received argument to B.
Is type casting a good programming technique ? If not what is the use of polymorphism here ?
Thanks.
Typecasting is only useful if you know what to cast into.
The use of polymorphism here is that the method in the other class can be written in a generic way, and a single piece of code can thus operate on different types, which, though, have some interface (class A) in common.
So… typecasting is (depending on language culture) a very bad practice. Use of polymorphism is preferred (depending…), such as creating a different method with signature
->(B), taking an argument of type B.Update: added Java pseudocode