Advanced OOP Concepts in Apex
Inheritance & Polymorphism
What Is Inheritance?
Inheritance allows a child class to reuse properties and methods of a parent class.
Simple Explanation
A child inherits features from parents.
Real-Life Example
-
Parent: Vehicle
-
Child: Car, Bike
Both are vehicles, but each behaves differently.
Code Example (Inheritance)
public class Vehicle {
public void move() {
System.debug('Vehicle is moving');
}
}
public class Car extends Vehicle {
public void move() {
System.debug('Car is driving');
}
}
What Is Polymorphism?
Polymorphism means one method behaves differently depending on the object type.
Vehicle v = new Car(); v.move(); // Output: Car is driving
Easy Rule to Remember
Inheritance = reuse
Polymorphism = different behavior
Gist (Quick Revision)
Inheritance reuses code; polymorphism changes behavior at runtime.
2. Interfaces
What Is an Interface?
An interface defines a contract that a class must follow.
Simple Explanation
An interface is a promise of what a class will do, not how it does it.
Real-Life Example
A charger socket:
-
Different chargers
-
Same plug shape
Code Example
public interface Payment {
void pay();
}
public class CreditCardPayment implements Payment {
public void pay() {
System.debug('Paid by credit card');
}
}
Why Interfaces Matter
-
Loose coupling
-
Flexible design
-
Easier testing
Gist (Quick Revision)
Interfaces define what must be implemented, not how.
3. Abstract Classes
What Is an Abstract Class?
An abstract class is a partial blueprint:
-
Cannot be instantiated
-
Can have abstract and normal methods
Simple Explanation
An abstract class says: “You must complete this method.”
Code Example
public abstract class Shape {
public abstract Decimal area();
}
public class Square extends Shape {
public override Decimal area() {
return 25;
}
}
Interface vs Abstract Class (Easy Comparison)
| Interface | Abstract Class |
|---|---|
| Only method signatures | Can have logic |
| Multiple interfaces allowed | Single inheritance |
| No variables | Can have variables |
Gist (Quick Revision)
Abstract classes provide shared logic + enforced rules.
4. Enums
What Is an Enum?
An enum is a fixed set of constant values.
Real-Life Example
Days of the week:
-
Monday
-
Tuesday
-
Wednesday
Code Example
public enum Status {
NEW,
IN_PROGRESS,
COMPLETED
}
Status currentStatus = Status.NEW;
Why Use Enums?
-
Prevent invalid values
-
Improve code readability
-
Reduce errors
Gist (Quick Revision)
Enums restrict values to a safe, predefined list.
