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.


 * 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;

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

class SuperClass{


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


Exception in thread "main" java.lang.ClassCastException: cannot be cast to
Subclass Method Called

Leave a Reply

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

Pin It on Pinterest

Share This

Share this post with your friends!