| |

Design Patterns in Salesforce: Mastering Inheritance in Apex (Ep. 4)

It has been a long time coming, but we are back with Episode 4 of the Design Patterns tutorial series! In this installment, we dive deep into one of the fundamental pillars of Object-Oriented Programming (OOP): Inheritance.

If you are an Apex developer looking to write cleaner, more efficient code, understanding inheritance is non-negotiable. Here is a breakdown of what it is, how to use it in Salesforce, and the potential pitfalls you need to avoid.

What is Inheritance?

At its simplest, inheritance is a mechanism that allows you to reuse code across multiple classes. Instead of writing the same logic over and over again for similar objects, you can write it once in a “parent” class and have other “child” classes automatically inherit that functionality.

Think of it as a family tree for your code. If a parent class has certain traits (methods and variables), the children get them for free, but they can also develop their own unique traits.

The “Car” Analogy

To explain this concept, the video uses a classic programming analogy: Cars.

Imagine you are building a racing game. You have hundreds of different cars—Lamborghinis, Buicks, Ferraris, etc.

  • Every car has wheels and doors.
  • Every car needs to Start and Stop.

Without inheritance, you would have to write the startCar() method inside every single car class. That is a nightmare to maintain.

With inheritance, you create a single Parent Class called Car that holds the shared logic. Then, your specific car classes (Lamborghini, Buick) simply “extend” the Car class. They get all the functionality without writing a single extra line of code.

Implementing Inheritance in Apex

In Salesforce Apex, implementing inheritance requires two specific keywords: virtual and extends.

1. The Parent Class (virtual)

By default, Apex classes cannot be inherited. You must explicitly mark the class as virtual. If you want a method to be overridable by child classes, that method must also be marked as virtual.

Apex

public virtual class Car {
    public Integer wheels = 4;
    public Integer doors = 4;

    public virtual void startCar() {
        System.debug('Car started');
    }

    public virtual void stopCar() {
        System.debug('Car stopped');
    }
}

2. The Child Class (extends)

To create a child class, use the extends keyword. This class now has access to everything in the Car class.

Apex

public class Buick extends Car {
    // This class is empty, but it can still call startCar()!
}

3. Overriding Methods (override)

What if a specific car needs to behave differently? For example, maybe your custom car is broken and shouldn’t start normally. You can override the parent’s logic using the override keyword.

Apex

public class BrokenCar extends Car {
    public override void startCar() {
        System.debug('This car is garbage and will not start.');
    }
}

A Real-World Salesforce Example: Lead Scoring

While cars are great for learning, how does this apply to your Salesforce org? A practical example is: Lead Scoring.

Imagine your organization has different departments—Sales and Marketing—that both need to score leads, but they do it slightly differently.

  1. Parent Class (LeadScore): Contains the core logic for finding a lead and saving the score.
  2. Child Class (MarketingLeadScore): Extends the parent but adds logic specific to marketing engagement.
  3. Child Class (SalesLeadScore): Extends the parent but focuses on sales readiness.

This structure prevents you from copying and pasting the “save score” logic into two different places.

The Warning: Don’t Overuse It!

Inheritance is fragile!

While it is great for code reuse, it can lead to the “God Class” problem, where you stuff too much functionality into a parent class. If you find that your child classes are inheriting 50 methods but only using 2 of them, inheritance might be the wrong tool. In those cases, a design pattern called Composition is often a better choice (a topic for a future video!).

Summary

  • Inheritance allows child classes to inherit properties and methods from a parent class.
  • Use the virtual keyword to define a parent class or method.
  • Use the extends keyword to define a child class.
  • Use the override keyword to change the behavior of an inherited method.
  • Best Use Case: When you have multiple classes that share significant common functionality (e.g., Lead Scorers).

Up Next: The series will continue by exploring Polymorphism and the Gang of Four design patterns.


Check out the full video here: Design Patterns in Salesforce (Ep. 4) – What is Inheritance?


Need help with your Salesforce Org?

If you need help with your Salesforce org, schedule an hour of consulting time with me! I’m one of only ~500 Salesforce Certified Technical Architect’s (CTA) worldwide and I’ve spent over 30,000 hours building Salesforce implementations over the last decade!

Schedule and hour of consulting with me here!


Do you want to be the next Salesforce Certified Technical Architect (CTA)?

If you need training to help you on your journey to complete your Salesforce CTA Board then why not sign up for the cheapest Salesforce CTA course out there, with someone who has training over a million Salesforce professionals worldwide! You can check out and enroll in the course below!

Sign up for the CTA course here!

Or if a course isn’t your thing, you can always sign up for an hour long CTA study session with me here:
Schedule 1-on-1 CTA Coaching Here!


Get Coding With The Force Merch!!

We now have a redbubble store setup so you can buy cool Coding With The Force merchandise! Please check it out! Every purchase goes to supporting the blog and YouTube channel.

Get Shirts Here!
Get Cups, Artwork, Coffee Cups, Bags, Masks and more here!


Check Out More Coding With The Force Stuff!

If you liked this post make sure to follow us on all our social media outlets to stay as up to date as possible with everything!

Youtube
Patreon
Github
Facebook
Twitter
Instagram


Salesforce Development Books I Recommend

Advanced Apex Programming
Salesforce Lightning Platform Enterprise Architecture
Mastering Salesforce DevOps

Good Non-SF Specific Development Books:

Clean Code
Clean Architecture


AI DISCLAIMER: Gemini assisted me in writing this blog post by analyzing and summarizing the contents on the YouTube video I created that is linked at the top of this post.

Similar Posts