Upcasting and Downcasting In Java with examples

Upcasting and Downcasting In Java with examples

Casting : Casting means assigning the object of one type to reference variable of another type.

Upcasting

In an upcasting child class object is assigned to the parent class reference variable. Java does automatic upcasting.

[java]
class A{

}
class B extend A{

}
A obj = new B();
[/java]

Downcasting

In downcasting, parent class object is assigned to the child class reference variable. We have to do downcasting manually.

[java]
class Parent{

}
class Child extend Parent{

}
Parent obj = new Child();
Child c = (Child)obj;
[/java]

Upcasting explanations

In an upcasting, child class object is assigned to the parent class reference variable. Java does automatic upcasting.

[java]
class A{

}
class B extend A{

}

A obj = new B();
[/java]

In the above example, you can see that upcasting happens automatically and we have not done anything explicitly for it.

We can call the methods of class ‘A’. At the runtime it will call the overridden method of class B.

There may be a chance that the method may not be overridden in child class. So in this case method of parent class which will be inherited to the child will be called.

Example of Upcasting

[c]
class Parent{
int x=20;
void display(){
System.out.println(“display method of parent class”);
}

void OnlyParentDisplay(){
System.out.println(“OnlyParentDisplay method of Parent”);
}
}

class Child extends Parent{
int x=40;
void display(){
System.out.println(“display method of Child class”);
}
void OnlyChildDisplay(){
System.out.println(“OnlyParentDisplay method of Child”);
}
}

public class Main {
public static void main(String[] args) {
Parent p = new Child();
p.display();
p.OnlyParentDisplay();
System.out.println(p.x);
}
}
[/c]

upcasting example in java

Downcasting Explanation with example

We cannot do downcasting directly in Java-like we do upcasting. As we have seen above the example of downcasting.

[java]
class Parent{

}
class Child extend Parent{

}
Child obj = new Parent();
[/java]

The above code will give an error compile-time error. This is not possible because all members of the child class are not present in the parent class. So to achieve upcasting we have to do first downcasting and then do the downcasting explicitly of the object.


Let’s see the example below on how we can achieve downcasting.

Parent p = new Child();
Child c =(Child) p;

Example of downcasting

[c]
class Animal { }
class Cat extends Animal {
static void method(Animal a) {
Cat d=(Cat)a;//downcasting
System.out.println(“downcasting performed”);
}
public static void main (String [] args) {
Animal a=new Cat();
Cat.method(a);
}
}
[/c]

Now I hope you have understood Upcasting and Downcasting In Java.