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 –

Output
Child’s show()
Downcasting in Java –

upcasting vs 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 –

Run Online

Output
ok downcasting performed

Leave a Reply

Your email address will not be published. Required fields are marked *