5

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?

1 Answer 1

8

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

6
  • Thanks for your plain explanation. I am still doubt that when can we cast apex objects like MyClass mc = (MyClass)JSON.deserialize('json string',MyClass.class);? or Apex does not support casting between custom apex objects?
    – Jun Ke
    Nov 1, 2015 at 3:27
  • @JunKe interesting, what's the use case your'e trying to build? Nov 1, 2015 at 3:31
  • I have a base class holding some common properties and methods, and some other classes extending the base class with specific properties or methods. There is a method returning the base class. I want to cast the return value to subtypes of the base class.
    – Jun Ke
    Nov 1, 2015 at 3:49
  • @JunKe maybe possible to use abstract base instead of virtual class, and then instantiate concrete children using Type.forName().newInstance() or such? Nov 1, 2015 at 4:20
  • Thank you, I seem to understand it, the method declared to return a supertype, and the actual return value is constructed in subtype. In this case the casting will work, am I right?
    – Jun Ke
    Nov 1, 2015 at 4:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .