Understanding Casting in Java

Understanding Casting in Java

In Java, Casting means to cast a class to another class. This definition has two catch points.


a. Can I cast any Java /custom type(class) to another Java/custom type: No You can only cast those classes to one another which are in the same inheritance tree. You can go back and forth but you are not allowed to cast one class to another type class. So you are able to cast child to parent or parent to child, but not able to cast between another type of class even siblings !!!!

Example :

Class A : Base class
Class B : subclass of A
Class C : subclass of A
Class D : Subclass of B

Then we can cast B to A and D but not C.

b. How many  types of Casting are there in Java:

There are two types of casting
a. Upcasting
b. DownCasting

Upcasting : When a Subclass is cast to parent that is called Upcasting. In Java, every polymorphic assignment is that type of casting. To do that you do not have to bother about explicit casting. this is logical because inheritance means inheriting   the properties of a parent into the child so you can easily say, property exists in the child also exists in the parent.

Subclass = parent properties  + it's own property

so ,

A a=null;
B b =new B(); //B extends A
a =b;//Up-casted no need to explicit casting.


DownCasting:
When a parent cast to its child it called downcasting and explicitly casting is needed here. It is logical as Parent does not know which child it needs to be cast more over parent does not know about Child's own properties.
so
Parent = subclass - Subclass own property


B b =null;   //B extends A
A a = new B();//polymorphic assignment.
b =(B)a; // need  explicit casting as ref a does not know about Object B.




Now add some complexity

Try to guess What will happen?

B b =null;   //B extends A
A a = new A();
b =(B)a; // need  explicit casting.

as although here, Compiler will not complain, but b reference holds an object of A, so when you called class B's own property through reference b. Actual  A object does not have that property and throws a run-time exception. So be careful about Downcasting.

Diagram