Home > Software design >  Polymorphism and casting object in Java
Polymorphism and casting object in Java

Time:12-13

is there any possibility that o1 or o2 can be casted to A and the program will run? Why is the last statement a runtime error?

public class A{
    public A(Object object)
    {
    
    }
    public A(){
    
    }
    public String toString(){
        return "A";
    }
}

  public class Main{
      public static void main(String []args){

          A a4 = new A();
          Object o1 = new Object();
          Object o2 = new A(o1);
    
          a4 = o1; //Compilation error
          o2 = o1;
          ((A)o1).toString();//Runtime error
          a4.toString();
          ((A)o2).toString();//Runtime error
}

}

CodePudding user response:

Is there any possibility of casting o1 or o2 to A ? That depends on when you try to do the cast.

      A a4 = new A();
      Object o1 = new Object();
      Object o2 = new A(o1);

       // o2 CAN be cast to A here

      o2 = o1;

      // o2 now CANNOT be cast to A here, since it is now referencing an object of type Object, not of type A

The last statement is an error, because the cast :

    (A)o2

Is a runtime error, since o2 at this point is referencing an Object, not an A.
Note that this cannot be a compilation error, since the syntax of the language means a variable of type Object MIGHT possibly be referencing an object of type A (so the cast MIGHT be valid)

  • Related