Java Downcasting | Java Upcasting | Casting objects & Difference with Examples

What is Java Casting?  

A casting means in the programming world taking one object and “turning it into” another object type without changing its values. When Talking about casting in Java it can do on Variables and Object. In Object there are further two types One is Java Downcasting and the second is Java Upcasting.

Definition of Type Casting  in one Line – “Typecasting is converting one data type to another.”

Java Downcasting Java Upcasting Difference and Examples casting

In this tutorial, we will learn about both Object casting and how they are related to Inheritance. Also looking the difference between down-casting and Up-casting in Java.

Before learning about it, we recommended reading this 2 tutorial first

Casting Terms:

Here is the code which we will consider the example for every casting in java.

What is Upcasting and Downcasting in Java
  • Animal class – SuperClass
  • Dog Class –  SubClass


The syntax of java casting objects.

Java downcasting

When converting a subclass to a superclass type is called an Upcasting in Java. Downward to the inheritance tree.

Let’s see an example. In Example, if the Animal class wants to invoke methods of the Dog class is called downcasting. Here we want a Dog bark() method, but the compiler will not allow it.

See below error when doing direct access method.

Java downcasting example error

To do it the right way is doing downcasting as below complete example.

Output: Dog bark

Why is Downcasting?

Downcasting in java used when we want to access specific behaviors of a subtype.

Java upcasting

And When Converting a superclass type to a subclass type is Called a Downcasting in Java.

Let’s see the example of Java Upcasting – subtype to the supertype. For that, we are casting Dog class to Animal type. There is no object change only reference changed.

Output: Dog says: Bow Bow

Why use an Upcasting? 

Generally, it’s not needed but when you want a deal with the only superclass then you can use it as an example.

Question: What is the use of upcasting and downcasting in java?

Answers: Generalization or UpCasting is a phenomenon where a subclass is prompted to a superclass, and hence becomes more general. Generalization needs widening or up-casting.

Specialization or DownCasting is a phenomenon where a superclass is narrowed down to a subclass. Specialization needs narrowing or down-casting.

Sidenote: This Tutorial you learn about casting objects in Java, for variable casting will post another tutorial.

Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1

Java version 11

All Java Downcasting and Java Upcasting Examples are in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.