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.

class A{

}
class B extend A{

}

A obj = new B();

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

class Parent{

}
class Child extend Parent{

}
Parent obj = new Child();
Child c = (Child)obj;

Lets see both upcasting and downcasting in detail with examples:

Upcasting:

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

class A{

}
class B extend A{

}

A obj = new B();

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.

Lets see an example how upcating works.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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);
    }
}
upcasting example in java

Downcasting:

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

class Parent{

}
class Child extend Parent{

}
Child obj = new Parent();

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:

1
2
3
4
5
6
7
8
9
10
11
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);  
  }  
}

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