In java consider example of car, where car is super class and Swift or Honda-City are sub classes.
it is true that Swift is of type car, so in Upcasting (which is changing type by moving up in the inheritance hierarchy).This is always safe because it is always true that SubType IS-A SuperType.
Therefore an explicit casting is NOT needed in up casting.
For Example:
SuperType x = new SubType();
Car y = new Swift();
Downcasting is changing type by moving down in the inheritance hierarchy.
This is not always safe, because its not always true that SuperType IS-A SubType(For Exampel car can not be always Swift). Therefore explicit casting is required.
For Example:
SubType s1 = (SubType)new SuperType();
or
Swift s1 = (Swift)new Car();
Though it will compile well, it may return ClassCastException during run time.
To avoid the same sometimes we use like this:
Car c1 = new Swift();
Swift s2 = (Swift)c1;
here above c1 is of type Car pointing to Swift instance, so casting it to subclass type is Ok.
No comments:
Post a Comment