xxxxxxxxxx
Upcasting is a type of object typecasting in which a child object is typecasted to a parent class object. By using the Upcasting, we can easily access the variables and methods of the parent class to the child class. Here, we don't access all the variables and the method. We access only some specified variables and methods of the child class. Upcasting is also known as Generalization and Widening.
xxxxxxxxxx
- Upcasting: Casting an object to base/upper hierarchy class. Valid
- Upcasting: Casting an object to derived/lower hierarchy class. May run into ClassCastingException.
- use: `if (obj instanceof ClassName){ // your downcasting logic }`
xxxxxxxxxx
// Upcasting is implicit
SportsCar sportcar = new SportsCar();
Car car = sportcar; // upcasting is implicit, this is OK!
sportcar.race(); // race() belongs to SportsCar, this is OK!
car.race(); // car may not race, will NOT compile!
// Downcasting is explicit
var myCar = new Car();
// a Car is not always a SportsCar. You may encounter runtime error
SportsCar mySportsCar = (SportsCar) myCar; // potential ClassCastingException
((SportsCar) car).race(); // downcasting to allow specialized subclass methods