Example & Tutorial understanding programming in easy ways.

How downcasting is possible in java?

 It helps to first define exactly what a downcast is. It’s actually pretty simple – suppose you have a base class, and a class that derives from that base class either directly or indirectly. Then, anytime an object of that base class type is type cast into a derived class type, it is called a downcast. The reason it’s called a downcast is because of the way that inheritance diagrams are normally written – base classes are at the top and derived classes are down below the base classes. So, in downcasting, you are going down the inheritance diagram by taking an object of a base class (at the top), and then trying to convert into the type of one of the derived classes (going down). The key word there is trying – because downcasting does not always make sense depending on the code being written. 

example:

 we have the following Java code in which a downcasting is being performed:

class home{ /* ... */}

class room extends home { /* ... */ }

public class Test {

public static void main (String args[ ]) {

home p = new home ( );

/*this is a downcast since the Parent class

object, "p" is being cast to a room type,

and room derives from the home class */

room c = (room) p;

}

}

Which of the following will happen with the code above:

1. It will compile and run without any errors
2. It will throw a compile time exception
3. It will throw a Runtime exception
 

In the code above, this line is where the downcast is being performed:

room c = (room) p;


  

Read More →