Upcast and downcast in java

What is Upcasting and Downcasting in Java

Perhaps in your daily Java coding, you see (and use) upcasting and downcasting occasionally. You may hear the terms ‘casting’, ‘upcasting’, ‘downcasting’ from someone or somewhere, and you may be confused about them.

As you read on, you will realize that upcasting and downcasting are really simple.

Before we go into the details, suppose that we have the following class hierarchy:

Mammal > Animal > Dog, Cat

Mammal is the super interface:

public abstract class Animal implements Mammal < public void eat() < System.out.println("Eating. "); >public void move() < System.out.println("Moving. "); >public void sleep() < System.out.println("Sleeping. "); >>
public class Dog extends Animal < public void bark() < System.out.println("Gow gow!"); >public void eat() < System.out.println("Dog is eating. "); >> public class Cat extends Animal < public void meow() < System.out.println("Meow Meow!"); >>

1. What is Upcasting in Java?

Upcasting is casting a subtype to a supertype, upward to the inheritance tree. Let’s see an example:

Dog dog = new Dog(); Animal anim = (Animal) dog; anim.eat();

Here, we cast the Dog type to the Animal type. Because Animal is the supertype of Dog , this casting is called upcasting.

Note that the actual object type does not change because of casting. The Dog object is still a Dog object. Only the reference type gets changed. Hence the above code produces the following output:

Читайте также:  Css flex выравнивание внутри блока

Upcasting is always safe, as we treat a type to a more general one. In the above example, an Animal has all behaviors of a Dog .

This is also another example of upcasting:

Mammal mam = new Cat(); Animal anim = new Dog();

2. Why is Upcasting in Java?

Generally, upcasting is not necessary. However, we need upcasting when we want to write general code that deals with only the supertype. Consider the following class:

public class AnimalTrainer < public void teach(Animal anim) < anim.move(); anim.eat(); >>

Here, the teach() method can accept any object which is subtype of Animal . So objects of type Dog and Cat will be upcasted to Animal when they are passed into this method:

Dog dog = new Dog(); Cat cat = new Cat(); AnimalTrainer trainer = new AnimalTrainer(); trainer.teach(dog); trainer.teach(cat);

3. What is Downcasting in Java?

Downcasting is casting to a subtype, downward to the inheritance tree. Let’s see an example:

Animal anim = new Cat(); Cat cat = (Cat) anim;

Here, we cast the Animal type to the Cat type. As Cat is subclass of Animal , this casting is called downcasting.

Unlike upcasting, downcasting can fail if the actual object type is not the target object type. For example:

Animal anim = new Cat(); Dog dog = (Dog) anim;

This will throw a ClassCastException because the actual object type is Cat . And a Cat is not a Dog so we cannot cast it to a Dog .

The Java language provides the instanceof keyword to check type of an object before casting. For example:

if (anim instanceof Cat) < Cat cat = (Cat) anim; cat.meow(); >else if (anim instanceof Dog)

So if you are not sure about the original object type, use the instanceof operator to check the type before casting. This eliminates the risk of a ClassCastException thrown.

4. Why is Downcasting in Java?

Downcasting is used more frequently than upcasting. Use downcasting when we want to access specific behaviors of a subtype.

Consider the following example:

public class AnimalTrainer < public void teach(Animal anim) < // do animal-things anim.move(); anim.eat(); // if there's a dog, tell it barks if (anim instanceof Dog) < Dog dog = (Dog) anim; dog.bark(); >> >

Here, in the teach() method, we check if there is an instance of a Dog object passed in, downcast it to the Dog type and invoke its specific method, bark() .

Okay, so far you have got the nuts and bolts of upcasting and downcasting in Java. Remember:

  • Casting does not change the actual object type. Only the reference type gets changed.
  • Upcasting is always safe and never fails.
  • Downcasting can risk throwing a ClassCastException , so the instanceof operator is used to check type before casting.

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Add comment

Comments

Dog dog = new Dog();
Animal anim = dog; //Enough
anim.eat(); // fails if eat() is not overridden. Try!!
two references anim and dog, are there now. reference does not ‘change’.
Entire article is absolute trash!

The Cat and Dog class below implement the Animal interface. All animals have names, but only dogs do tricks. Implement the describe method, using the instanceof operator to test whether the given animal is a dog. If so, return the name, a space, and the trick that the dog can do, such as «Helmut barks at the moon». If it is any other kind of animal, return the name, a space, and «has no tricks».

Chào Duc,
Downcasting được dùng thường xuyên em ạ. Phổ biến trong hàm equals(). Em xem ví dụ ở bài viết này: codejava.net/. /.

Đọc qua bài của anh em vẫn chưa hiểu tại sao lại phải cần sử dụng downcasting? Tại sao không sử dụng luôn upcasting đi?

Nếu được anh có thể cho em một vài ví dụ cụ thể không?

Your example is illogical — if you’re going to use real-world examples, the words have meanings. All mammals are animals, but not all animals are mammals. You should start with Animal > Mammal > Dog.

Источник

Upcasting and Downcasting in Java with Example

Scientech Easy

When the reference variable of super class refers to the object of subclass, it is known as widening or upcasting in java.

In other words, when the subclass object type is converted into superclass type, it is called widening or upcasting.

Upcasting in java

Look at the below figure, where superclass reference is pointing to the subclass object.

Let’s understand it with the help of a suitable example. Suppose class One and class Two are related classes through inheritance. class One is a superclass and class Two is subclass of One.

1. Super class reference is used to refer to superclass object.

In the above statement, class One’s reference o is pointing or referring to One’s object.

2. Similarly, sub class reference is used to point to sub class object.

In this statement, class Two’s reference t is pointing to Two’s object.

In the above two statements, we do not need casting. This is because on the left side and at the right side of assignment operator (=), we have the same data type.

For example, in the first statement, o is a reference of class One. So, data type of o is One.

At right side of assignment operator, we have class One’s object. Data type of the class object is also One. Therefore, casting is not required in this case.

Till here, there is no need for casting. But when a reference of class refers to different class’s object, we need casting.

One o = new Two(); // class One's reference o is pointing to class Two's object.

In this statement, on the left side, the data type of reference o is One but on the right side, we got object whose data type is Two. So, in this case, we will need casting.

We will convert object’s data type into class O using cast operator. It can be done like this:

One o = (One) new Two(); // Converting class Two's type into class One.

Here, sub class object type has converted into super class type. This kind of conversion is called upcasting or widening in java.

If we do not use the cast operator in the above case, even we will not get any error message. Java compiler will do the implicit casting.

Example Based on Upcasting (Widening)

Let’s take an example program to see the effect of upcasting where super class reference refers to sub class object.

Program code 1:

package classCasting; public class One < void m1() < System.out.println("m1 method in class One"); >> public class Two extends One < void m2() < System.out.println("m2 method in class Two"); >> public class Test < public static void main(String[] args) < One o = (One)new Two(); // Upcasting. Here, super class reference o refers to sub class object. o.m1(); // o.m2(); // Compile-time error message. >>
Output: m1 method in class One

In this example program, superclass reference is pointing to subclass object. This means that sub class object type is converted into super class type. Now, observe that we are able to call m1() method of super class.

But when we are trying to call m2() method of sub class, we got error message: compile-time error. Hence, in upcasting or widening, we can call all methods of super class but not sub class methods.

Let’s take another program where we will override super class method in sub class and will observe that can we access super class method and sub class method.

Program code 2:

package classCasting; public class One < void m1() < System.out.println("m1 method in class One"); >> public class Two extends One < void m1() < System.out.println("m1 method in class Two"); >> public class Test < public static void main(String[] args) < One o = (One)new Two(); // Upcasting. Here, super class reference o refers to sub class object. o.m1(); >>
Output: m1 method in class Two

As you can observe in the program that it is possible to access sub class method but not super class method when super class method is overridden in sub class. This shows that you can access only 50% of the functionality.

Downcasting (Narrowing) in Java

When subclass reference refers to super class object, it is called narrowing or downcasting in java. In other words, when sub class type is converted into super class type, it is called downcasting.

Look at the below figure where subclass reference is pointing to superclass object.

Downcasting in Java

Here, we are converting superclass object type into subclass type. Therefore, we need a compulsory cast operator. If we perform it directly, Java compiler will give compile-time error.

Let’s consider the above example program where we will do downcasting and see what happens?

Program code 3:

package classCasting; public class One < void m1() < System.out.println("m1 method in class One"); >> public class Two extends One < void m2() < System.out.println("m2 method in class Two"); >> public class Test < public static void main(String[] args) < Two t = (Two) new One(); // Downcasting. Here, subclass reference t refers to superclass object. t.m1(); t.m2(); >>
Output: Exception in thread "main" java.lang.ClassCastException: classCasting.One cannot be cast to classCasting.Two

In the above example program, we have performed downcasting directly. Therefore, JVM is thrown an exception named ClassCastException at runtime.

So, in the case of downcasting, we cannot access any of the methods of super class or sub class. So, let’s understand how downcasting is possible in java?

How Downcasting is possible?

To overcome this problem, we will have to modify the previous code. So, look at the following source code and modify it.

Program code 4:

package classCasting; public class One < void m1() < System.out.println("m1 method in class One"); >> public class Two extends One < void m2() < System.out.println("m2 method in class Two"); >> public class Test < public static void main(String[] args) < One o = new Two(); // Super class reference refers to sub class object. Two t = (Two)o; // Converting super class reference type into sub class reference type. t.m1(); // Calling m1 method using reference variable of sub class. t.m2(); // Calling m1 method using reference variable of sub class. >>
Output: m1 method in class One m2 method in class Two

In the above program, superclass reference type has converted into sub class reference type. Now, we can call both methods m1() and m2() using reference variable of sub class.

In the preceding code, you can observe that if we create an object of subclass, it is possible to access all the methods of super class and subclass. In this way, downcasting is possible in java.

Hope that this tutorial has covered almost all important points associated with upcasting and downcasting in java with example program.

I hope you will have understood to perform Java upcasting and downcasting nicely and enjoyed related programming.
Thanks for reading. Next ⇒ Method overriding in Java ⇐ PrevNext ⇒

Источник

Оцените статью