function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

Extending Apex Classes

Please help me understand what is going on here.  According to the documentation this code should work with no issues.  I am trying to cast a return value of type parent class to a child class variable.  This code compiles fine but throws 


System.TypeException: Invalid conversion from runtime type Class1Test to Class1ExtensionTest


Here is the sample code



public virtual class Class1Test {

private string sCopy;
public Class1Test(string s){
sCopy = s;

public class Class1ExtensionTest extends Class1Test{

public Class1ExtensionTest(string s){

public class TestClass{

public static testmethod void testmethod(){
Class1Test.Class1ExtensionTest t = (Class1Test.Class1ExtensionTest)testCasting();

private Class1Test testCasting( ){
return new Class1Test('This Should work');




You seem to have it back to front, your actual instance is an instance of the base class, you can't cast this to an instance of a sub-class, as it isn't a subclass.

Doesn't the documentation say otherwise?  It looks like they are casting a base object to a sub class object.  Is it because it was first an instance of the sub class before it was put in a collection of type base class?
RIght, in the docs example they actually create an instance of the subclass, not the base type.



Can you please tell me if there is any way to create an instance of the base class.