Inheritance
By the end of this lesson, you'll be able to:
- Write a subclass that extends a parent class using extends
- Explain what a subclass automatically gets from its parent
- Recognize inheritance as a way to model an "is-a" relationship
Prerequisites: "Encapsulation"
A parent class and a subclass
public virtual class Vehicle {
public String licensePlate;
public void startEngine() {
System.debug('Engine started.');
}
}
public class DeliveryVan extends Vehicle {
public Decimal cargoCapacityKg;
}
DeliveryVan van = new DeliveryVan();
van.licensePlate = 'CA 123-456'; // inherited from Vehicle
van.startEngine(); // inherited from Vehicle
van.cargoCapacityKg = 1200; // defined on DeliveryVan itself
DeliveryVan extends Vehicle means every DeliveryVan automatically has everything Vehicle defines — licensePlate and startEngine() — plus its own cargoCapacityKg. The parent class must be marked virtual (covered in the next lesson) for another class to extend it at all.
The "is-a" test
Inheritance models a genuine is-a relationship: a DeliveryVan is a Vehicle. If that sentence doesn't sound natural for two classes, they probably shouldn't inherit from each other — a Driver is not a Vehicle, for example, even though a driver operates one. That relationship belongs to a different pattern (composition, covered later in this module).
A real business example: Media (Publishing)
public virtual class Publication {
public String title;
public String getCitation() {
return title;
}
}
public class Magazine extends Publication {
public Integer issueNumber;
}
public class Newspaper extends Publication {
public Date publishDate;
}
Both Magazine and Newspaper genuinely are publications, sharing a title and a citation method, while each adds its own specific data — exactly the shape inheritance is meant for.
Exercise
Write a virtual class Employee with a public String name and a method describe() returning name. Write a subclass Manager extends Employee that adds a public Integer teamSize.
Show hint
public class Manager extends Employee { public Integer teamSize; }
Inheritance Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
Inheritance lets one class (a subclass) automatically get the fields and methods of another (its parent class), then add or change behavior of its own — modeling a genuine "is-a" relationship between things.