Upcasting vs Downcasting in Java
In the java programming article we will discuss in detail the concept of Upcasting vs Downcasting in Java Programming. We will also check out some basic examples and diagrams to understand the difference between the two concepts.
Upcasting in Java –
Upcasting is casting a subtype to a supertype, upward to the inheritance tree. Upcasting happens automatically and we don’t have to explicitly do anything. Let us see a program snippet –
// Base Class class Parent { void show() { System.out.println("Parent's show()"); } } // Inherited class class Child extends Parent { // This method overrides show() of Parent @Override void show() { System.out.println("Child's show()"); } } class Main { public static void main(String[] args) { Parent obj1 = new Child(); obj1.show(); } }
Downcasting in Java –
When Subclass type refers to the object of Parent class, it is known as downcasting. If we perform it directly, compiler gives Compilation error. If you perform it by typecasting, ClassCastException is thrown at runtime. But if we use instanceof operator, downcasting is possible.
Lets see a simple program example –
class Animal { } class Dog3 extends Animal { static void method(Animal a) { if(a instanceof Dog3){ Dog3 d=(Dog3)a;//downcasting System.out.println("ok downcasting performed"); } } public static void main (String [] args) { Animal a=new Dog3(); Dog3.method(a); } }