Search code examples
javadowncast

Downcasting objects in Java


class A{

}

public class Demo 
{
  public static void   main(String s[])
  {         
      Object o=(Object) new Demo();
      if (((A)(o)) instanceof Object) 
      {
           System.out.println("true");
      }
  }
}

I am getting Exception while running the class Demo.java:

java.lang.ClassCastException: Demo cannot be cast to A

How to downcast o reference to class A?


Solution

  • Let's start from the beginning: This is terrible code. That being said:

    • You are casting Demo to Object (for whatever reason, since in Java everything is Object, no need to cast).
    • You are then casting o, that you know it's of type Demo, to A (why would this work?).
    • You are checking if Object o is of type Object (why would this fail?)

    Some notes:

    • o should not be viewed as a reference, it is an instance of Object, as you declared it. Forget how things worked in C.
    • Consider interfaces and if you want A to be an interface that Demo implements.
    • You can only cast instances to a class that they already extend.

    Downcast example:

        public class A {
        int variable = 0; 
    }
    
    public class Demo extends A{
    
    }
    
    public void testDowncast(){
        Demo myClass = new Demo();
        myClass.variable = 2;
        A morphingTime = myClass;
        System.out.println("And now Power Ranger Demo has turned into Mighty A:");
        System.out.println("I am: "+morphingTime.getClass() + " and my variable is: " + morphingTime.variable);
    }