UpCasting and DownCasting
Upcasting
- An object of a sub class can be referred by its super class automatically.
- You can cast an object implicitly to a super class type is Called UpCasting.
- If this were not the case polymorphism wouldn't be possible.
- When up casting primitives from left to right, automatic conversion done as below:-
byte -> short -> int -> long -> float -> double
int i = 10;
long j = 15; //Correct. Up casting or implicit casting
byte c1 = i; //Incorrect. Compile time error " Type Mismatch".
byte c2 = (byte) i ; //Correct. Down casting or explicit casting is required.
int i = 10;
long j = 15; //Correct. Up casting or implicit casting
byte c1 = i; //Incorrect. Compile time error " Type Mismatch".
byte c2 = (byte) i ; //Correct. Down casting or explicit casting is required.
Downcasting
- Explicit casting is to be done by the super class.
- Which is performed manually by the developers.
UpCasting vs DownCasting:-
Vehicle v1 = new Car(); //Right.upcasting or implicit casting
Vehicle v2 = new Vehicle();
Car c0 = v1; //Wrong. compile time error "Type Mismatch".
//Explicit or down casting is required
Car c1 = (Car)v1; // Right. down casting or explicit casting.
// v1 has knowledge of Car due to line1
Car c2 = (Car)v2; //Wrong. Runtime exception ClassCastException
//v2 has no knowledge of Car.
Bus b1 = new Alto(); //Wrong. compile time error "Type Mismatch"
Car c3 = new Alto(); //Right.upcasting or implicit casting
Car c4 = (Alto)v1; //Wrong. Runtime exception ClassCastException
Object o = v1; //v1 can only be upcast to its parent or
Car c5 = (Car)v1; //v1 can be down cast to Car due to line 1.
Vehicle v2 = new Vehicle();
Car c0 = v1; //Wrong. compile time error "Type Mismatch".
//Explicit or down casting is required
Car c1 = (Car)v1; // Right. down casting or explicit casting.
// v1 has knowledge of Car due to line1
Car c2 = (Car)v2; //Wrong. Runtime exception ClassCastException
//v2 has no knowledge of Car.
Bus b1 = new Alto(); //Wrong. compile time error "Type Mismatch"
Car c3 = new Alto(); //Right.upcasting or implicit casting
Car c4 = (Alto)v1; //Wrong. Runtime exception ClassCastException
Object o = v1; //v1 can only be upcast to its parent or
Car c5 = (Car)v1; //v1 can be down cast to Car due to line 1.


