Newer Version Available

This content describes an older version of this product. View Latest

Classes and Casting

In general, all type information is available at run time. 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 subclass 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 subclass of that class. This means that you can use casting to assign objects with the parent data type (Report) to the objects of the subclass data type (CustomReport).

In the following code segment, a custom report object is first added to a list of report objects. Then the custom report object is returned as a report object, which is then cast back into a custom report object.

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.

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

Tip