Understanding Inheritance in Salesforce Apex

Understanding Inheritance in Salesforce Apex
Chinmaya By Chinmaya
9 Min Read

Introduction

Inheritance is one of the core concepts of Object-Oriented Programming (OOP) and is also supported in Salesforce through Apex, its programming language.

Inheritance allows you to create a new class (called a child class) that inherits properties and methods from an existing class (called a parent class). This promotes code reusability and makes your code more organized and maintainable.

In this blog, we’ll explore:

    • What is inheritance?
    • Why use inheritance in Apex?
    • How inheritance works in Apex.
    • Examples of inheritance in Apex.
    • Best practices when using inheritance.

1. What is Inheritance?

Inheritance is a mechanism where a new class derives properties and behaviors (methods) from an existing class. The existing class is called the parent class (or base class), and the new class is called the child class (or subclass).

The child class can:

    • Access the public and protected members of the parent class.
    • Override the parent class’s methods to provide specific implementations.
    • Add additional methods and properties unique to itself.

2. Why Use Inheritance in Apex?

Inheritance offers several benefits:

    • Code Reusability: Common functionality can be defined in a base class and reused in derived classes.
    • Scalability: You can extend the functionality of the parent class by adding new methods or properties in the child class.
    • Maintainability: Reduces code duplication, making it easier to manage and update.

3. How Does Inheritance Work in Salesforce Apex?

In Salesforce, inheritance is implemented using the extends keyword. When a child class extends a parent class, it inherits all the non-private methods and properties of the parent class. The child class can also override the parent class’s methods to provide its own implementation.

Access Modifiers:

    • Public/Protected: Accessible in the child class.
    • Private: Not accessible in the child class.

Method Overriding: Child classes can override parent methods using the @Override annotation.

4. Examples of Inheritance in Salesforce Apex

Example 1: Basic Inheritance

Let’s create a parent class Animal and a child class Dog.

				
					// Parent Class
public class Animal {
    public String name;

    public void eat() {
        System.debug(name + ' is eating.');
    }
}

// Child Class
public class Dog extends Animal {
    public void bark() {
        System.debug(name + ' is barking.');
    }
}

// Test Class
public class InheritanceExample {
    public static void runExample() {
        Dog dog = new Dog();
        dog.name = 'Buddy';
        dog.eat();  // Inherited from Animal
        dog.bark(); // Specific to Dog
    }
}
				
			

Output:

				
					Buddy is eating.
Buddy is barking.
				
			

Example 2: Overriding Methods

The child class can override a method from the parent class to provide specific functionality.

				
					// Parent Class
public class Animal {
    public void makeSound() {
        System.debug('Animal is making a sound.');
    }
}

// Child Class
public class Dog extends Animal {
    @Override
    public void makeSound() {
        System.debug('Dog is barking.');
    }
}

// Test Class
public class OverridingExample {
    public static void runExample() {
        Animal genericAnimal = new Animal();
        genericAnimal.makeSound(); // Outputs: Animal is making a sound.

        Animal dog = new Dog();
        dog.makeSound(); // Outputs: Dog is barking.
    }
}
				
			

Example 3: Using Protected Members

Protected members can be accessed by child classes but not outside the class hierarchy.

				
					// Parent Class
public class Animal {
    protected String sound;

    public void setSound(String sound) {
        this.sound = sound;
    }
}

// Child Class
public class Cat extends Animal {
    public void makeSound() {
        System.debug('Cat says: ' + sound);
    }
}

// Test Class
public class ProtectedExample {
    public static void runExample() {
        Cat cat = new Cat();
        cat.setSound('Meow');
        cat.makeSound(); // Outputs: Cat says: Meow
    }
}
				
			

Example 4: Abstract Classes

Abstract classes are partially implemented classes that can be extended by other classes.
They are useful when you want to enforce a structure for your child classes.

				
					// Abstract Parent Class
public abstract class Animal {
    public abstract void makeSound(); // Abstract method

    public void eat() {
        System.debug('This animal is eating.');
    }
}

// Child Class
public class Dog extends Animal {
    @Override
    public void makeSound() {
        System.debug('Dog is barking.');
    }
}

// Test Class
public class AbstractExample {
    public static void runExample() {
        Animal dog = new Dog();
        dog.makeSound(); // Outputs: Dog is barking.
        dog.eat();       // Outputs: This animal is eating.
    }
}
				
			

5. Key Points to Remember About Inheritance in Salesforce:

  1. Access Modifiers:

    • Only public and protected methods and properties are inherited. Private members are not accessible in the child class.

  2. Method Overriding:

    • A child class can override a method from the parent class by using the override keyword.

  3. Constructor Chaining:

    • The child class constructor must call the parent class constructor using super() if the parent class has a parameterized constructor.

  4. Single Inheritance:

    • Salesforce Apex supports single inheritance, meaning a child class can extend only one parent class.

6. Why is Inheritance Important in Salesforce?

Inheritance is a powerful concept that helps you:

    • Reuse code: Avoid duplicating code by inheriting from existing classes.

    • Organize code: Create a clear hierarchy of classes, making your code easier to understand and maintain.

    • Extend functionality: Add new features to existing classes without modifying them.

7. Best Practices for Inheritance in Apex

1. Use Inheritance Wisely

    • Avoid creating deep inheritance hierarchies, as they can become difficult to manage.
    • Use inheritance only when there is a clear “is-a” relationship (e.g., a Dog “is-an” Animal).

2. Use Abstract Classes for Shared Structure:

    • Define abstract methods in the parent class to enforce structure in child classes.
    • Combine abstract and concrete methods for flexibility.

3. Leverage @Override Annotation:

    • Always use the @Override annotation to clearly indicate that a method is being overridden.

4. Favour Composition Over Inheritance:

    • If the relationship between classes is more “has-a” than “is-a,” use composition instead of inheritance.

Example of Composition

				
					public class Engine {
    public void start() {
        System.debug('Engine started.');
    }
}

public class Car {
    private Engine engine = new Engine();

    public void drive() {
        engine.start();
        System.debug('Car is driving.');
    }
}
				
			

5. Minimize Code Duplication:

    • Move common methods or properties to the parent class to maximize code reuse.

6. Avoid Overusing Protected Access:

    • Use protected access sparingly, as it can make the code harder to refactor.

8. Real-World Scenario

Scenario 1:

Imagine you’re building a Salesforce application to manage different types of employees in an organization. You could create a parent class called Employee with common properties like namesalary, and methods like calculateBonus(). Then, you could create child classes like ManagerDeveloper, and SalesRep that inherit from the Employee class and add their own specific properties and methods.

Scenario 2: Managing Different Types of Payments

Let’s build an inheritance model for processing payments.

				
					// Abstract Parent Class
public abstract class PaymentProcessor {
    public abstract void processPayment();

    public void commonMethod() {
        System.debug('Performing common pre-processing.');
    }
}

// Child Class 1
public class CreditCardPayment extends PaymentProcessor {
    @Override
    public void processPayment() {
        System.debug('Processing credit card payment.');
    }
}

// Child Class 2
public class PayPalPayment extends PaymentProcessor {
    @Override
    public void processPayment() {
        System.debug('Processing PayPal payment.');
    }
}

// Test Class
public class PaymentExample {
    public static void runExample() {
        PaymentProcessor creditCard = new CreditCardPayment();
        PaymentProcessor paypal = new PayPalPayment();

        creditCard.commonMethod();
        creditCard.processPayment();

        paypal.commonMethod();
        paypal.processPayment();
    }
}
				
			

Output:

				
					Performing common pre-processing.
Processing credit card payment.
Performing common pre-processing.
Processing PayPal payment.
				
			

Conclusion

Inheritance is a fundamental concept in Object-Oriented Programming and Salesforce Apex. It allows you to create a hierarchy of classes, reuse code, and extend functionality in a clean and organized way. By mastering inheritance, you can write more efficient and maintainable code in Salesforce.

Whether you’re building custom applications or working on complex business logic, understanding inheritance will help you design better solutions. Keep practicing and experimenting with inheritance to unlock its full potential!

Share This Article
Follow:
Chinmaya is working as a Senior Consultant with a deep expertise in Salesforce. Holding multiple Salesforce certifications, he is dedicated to designing and implementing cutting-edge CRM solutions. As the creator of Writtee.com, Chinmaya shares his knowledge on educational and technological topics, helping others excel in Salesforce and related domains.
Leave a comment