Class HierarchiesReading Only
SubscriptionProduct os = new SubscriptionProduct('Operating System', 500.00); ServiceProduct itSupport = new ServiceProduct('IT Support', 150.00, 100); HardwareProduct laptop = new HardwareProduct('Laptop', 899.00); List<Product> products = new List<Product>(); products.add(os); products.add(itSupport); products.add(laptop);
The code above was possible because SubscriptionProduct
, ServiceProduct
, and HardwareProduct
are all subclasses of Product
. These are specialized versions of the superclass Product
. They inherit methods and attributes from the superclass and can have their own additional methods or attributes.
A superclass may also be referred to as a parent class or a base class. Its purpose is to represent the general concept that forms the abstraction. As you'll see in the next course, these are made possible in Apex through Interfaces, Virtual Classes, and Abstract Classes.
This parent-and-child relationship forms a class hierarchy that represents the relationships of inheritance. Even though SubscriptionProduct
doesn't have a method called calculateTotalPrice
, the code still compiles because the method is inherited from the parent class.
SubscriptionProduct sp = new SubscriptionProduct('OS Software - 1 Year', 500.00); Decimal totalPrice = sp.calculateTotalPrice();
The attributes and methods of a super class can be referenced from the subclass by using the super
keyword.
Below, we're using super()
to call the Product's constructor. This is useful if you've placed important functionality into the superclass's constructor.
public class SubscriptionProduct extends Product { public SubscriptionProduct(String name, Decimal price){ super(name, price); // This calls Product's constructor } }
Within the class hierarchy, a subclass is also a subtype. This relationship implies that objects of the subtype can be used wherever objects of the supertype are expected. This allows for polymorphism, where an interface can be used to represent different subtypes. Instead of explicitly referencing HardwareProduct
, we can reference its parent, Product
.
List<Product> products = new List<Product>(); products.add(os); // os is an instance of SubscriptionProduct products.add(itSupport); // itSupport is an instance of ServiceProduct products.add(laptop); // laptop is an instance of HardwareProduct
It also makes this possible:
Product myProduct = new HardwareProduct('Laptop', 899.00); Decimal totalPrice = myProduct.calculateTotalPrice();
This compiles because HardwareProduct
is a subtype of Product
. Again, don't stress over the syntax. We'll cover that in a bit.