Classes and Casting

In general, all type information is available at runtime. This means that Apex enables casting, that is, a data type of one class can be assigned to a data type of another class, but only if one class is a child of the other class. Use casting when you want to convert an object from one data type to another.

In the following example, CustomReport extends the class Report. Therefore, it is a child of that class. This means that you can use casting to assign objects with the parent data type (Report) to the objects of the child data type (CustomReport).

In the following code block, first, a custom report object is added to a list of report objects. After that, the custom report object is returned as a report object, then is cast back into a custom report object.

Public virtual class Report {

   Public class CustomReport extends Report {
   // Create a list of report objects
      Report[] Reports = new Report[5];

   // Create a custom report object
      CustomReport a = new CustomReport();

   // Because the custom report is a sub class of the Report class,
   // you can add the custom report object a to the list of report objects
      Reports.add(a);

   // The following is not legal, because the compiler does not know that what you are 
   // returning is a custom report. You must use cast to tell it that you know what
   // type you are returning
   // CustomReport c = Reports.get(0);

   // Instead, get the first item in the list by casting it back to a custom report object
      CustomReport c = (CustomReport) Reports.get(0);
   }
}
Casting Example A flowchart of the Apex casting process

In addition, an interface type can be cast to a sub-interface or a class type that implements that interface.

Tip

Tip

To verify if a class is a specific type of class, use the instanceOf keyword. For more information, see Using the instanceof Keyword.

Previous
Next