[SalesForce] Invalid conversion from runtime type

I basically have the same problem that was described here Invalid conversion from runtime type MyClass.A to MyClass.B but i'm unclear as to what the solution is

I have a virtual class A and classes B and C that both extend A. A has some fields, B and C do nothing have anything in them and are only used for the class name.

I have a method which return an A object. I then want to cast this object into a B and a C. Why am i getting this error?

example code

public virtual class A {
   //fields
}

public class B extends A {
   //nothing
}

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

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

EDIT: apparently the solution is to create another helper method that will take a parent object as an argument. You create a child object, modify that object in your method (you can modfy both chil objects in the same way), return it as an object and then cast that object back into a child. Idk why but that worked.

Best Answer

This is the expected behavior for any Object Oriented Programming.

What you have currently returning from your method is the instance of the Parent Class, and thus it cannot be cast to an instance of Child Class.

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

Only if you had your method something as below, it would have then worked.

public A someMethod(){
   return new B(); // returns instance of B
}
Related Topic