Downcasting In Java

Upcasting is assigning the sub class reference object to the parent class which is allowed in Java. Downcasting is assigning parent class reference object to the sub class which is not allowed in Java. However, if you do downcasting, there will not be any compiler error. But, there will be runtime exception java.lang.ClassCastException. Then why downcasting is permitted without any compiler error?. Downcasting is legal in some scenarios where the actual object referred by the parent class is of sub class.

Look at this example to understand when downcasting works without any exception.

DownCastingExample.java

package javabeat.net.core;

/**
 * Java DownCasting Example
 *
 * @author Krishna
 *
 */
public class DownCastingExample {

	public static void main(String[] args) {
		SuperClass superClass1 = new SuperClass();
		SuperClass superClass2 = new SubClass();

		//Valid down casting
		SubClass subClass1 = (SubClass)superClass2;
		subClass1.method();

		//Invalid down casting
		SubClass subClass2 = (SubClass)superClass1;
	}
}

class SuperClass{

}

class SubClass extends SuperClass{
	public void method(){
		System.out.println("Subclass Method Called");
	}
}

Output…

Exception in thread "main" java.lang.ClassCastException: infosys.net.core.SuperClass cannot be cast to infosys.net.core.SubClass
	at javabeat.net.core.DownCastingExample.main(DownCastingExample.java:20)
Subclass Method Called

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*