Java Type Casting : Inheritance

Converting one type of value to another is called as Type Casting.

Different Forms of Type Casting :

There are two types of type casting.
Type Casting - Different Forms

Live Example of Type Casting in Inheritance :

package com.c4learn.inheritance;
class Vehicle {
	String nameOfVehicle;	
}
class TwoWheeler extends Vehicle {
	String vehicleModel;	
}
public class TypeCastExample {
    public static void main(String[] args) {
    	Vehicle    v1 = new  Vehicle();
    	Vehicle    v2 = new  TwoWheeler();
    	TwoWheeler v3 = (TwoWheeler) new  Vehicle();
    	TwoWheeler v4 = new  TwoWheeler();
    }
}

A. Up Casting :

You can cast an instance of a child class to its parent class. Casting an object of child class to a parent class is called upcasting.

Consider the following example, Assuming that TwoWheeler is a subclass of Vehicle.

Vehicle    v2 = new  TwoWheeler();

B. Down Casting :

Casting an object of a parent class to its child class is called downcasting.

Consider the following example, Assuming that TwoWheeler is a subclass of Vehicle. Following is an example of the down casting -

TwoWheeler v3 = (TwoWheeler) new  Vehicle();