[SalesForce] Invalid conversion from runtime type MyClass.A to MyClass.B

I have a class as follows.

public class MyClass{

   public virtual class A{}

   public class B extends A{}

   public A someMethod(){
      return new A();
   }

   public void myMethod(){
      B b1 = (B)someMethod();
   }
}

When executing myMethod(), i got this runtime error:

Invalid conversion from runtime type MyClass.A to MyClass.B

I think as B is a child of A, instances of A can be cast to B.

Am I wrong? Why I got this error?

Best Answer

You've got the right idea, just a technicality in one direction.

I try and put a familiar analogy in my head for these things, eg:

  • all Accounts are SObjects
  • not all SObjects are Accounts.

You can get lucky at runtime if and only if you cast (Account) something that really is an Account.


If apex unilaterally permitted A to B casting at runtime, the B behaviours could be very ill defined.

His stuff that makes him a B (properties etc) could be missing. Exception thrown, surprise averted ;)