Upcasting and DownCasting In Java

Upcasting and DownCasting In Java:-

It is one of the most popular interview questions in Java. We will talk about  Up casting and Down Casting in Java.

Let’s have a look at the problem or rather question.

What would be the Output ? If you know the answer then i think you are not the target audience here and you can skip this post.

Answer:-

For Point 2 there will be a compilation Error as well as runtime error.

Let’s discuss why ?

What is Upcasting & Downcasting Here:-

Upcasting is casting to a supertype, while downcasting is casting to a subtype. Upcasting is always allowed, but downcasting involves a type check and can throw a ClassCastException.

In your case, a cast from Man to an Animal is an upcast, because of a Man is-a Animal In general, you can upcast whenever there is an is-a relationship between two classes.

We will now resolve both the  Issues.

1. Bypass Compilation Issue by Casting:-

So the Code Looks Like:-

Here you Will get a ClassCastException The reason why is because animal‘s runtime type is,Animal .Now at runtime, it performs the cast and it seems that animal isn’t really a Man and so throws a ClassCastException .

We can use the instanceof operator to check the runtime type of the object before performing the cast, which allows you to prevent ClassCastException.

Note: –We can use the instanceof operator to check the runtime type of the object before performing the cast, which allows you to prevent ClassCastException

2. ByPass the Runtime Error:-

So the Updated and Corrected Code would look like,

Explanation:-

So what happens here,

Basically, we are telling the compiler that we know runtime type of the object. Hence we don’t get a compilation error here. There will not be any runtime error as , the cast is possible because at runtime animalis actually a Man even though the static type of animal is Animal.

 

 

 

 

 

 

 

Leave a Reply

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