Apex Interfaces and Inheritance
Apex Interfaces and Inheritance are fundamental object-oriented programming concepts essential for the Salesforce Certified Platform Developer I exam, particularly in Process Automation and Logic. **Inheritance** allows an Apex class to extend another class using the 'extends' keyword, inheriting … Apex Interfaces and Inheritance are fundamental object-oriented programming concepts essential for the Salesforce Certified Platform Developer I exam, particularly in Process Automation and Logic. **Inheritance** allows an Apex class to extend another class using the 'extends' keyword, inheriting its methods and properties. The child class (subclass) can reuse, override, or extend the behavior of the parent class (superclass). Apex supports single inheritance, meaning a class can only extend one parent class. The 'virtual' keyword allows a class or method to be overridden, while 'override' is used in the child class to redefine the method. The 'super' keyword references the parent class's methods or constructors. Example: virtual class Animal { virtual String speak() { return 'sound'; } } class Dog extends Animal { override String speak() { return 'Bark'; } } **Interfaces** define a contract of methods that implementing classes must fulfill. They are declared using the 'interface' keyword and contain method signatures without implementations. A class implements an interface using the 'implements' keyword and must provide concrete implementations for all defined methods. Unlike inheritance, a class can implement multiple interfaces, enabling a form of polymorphism. Example: interface Loggable { void log(String message); } class ConsoleLogger implements Loggable { public void log(String message) { System.debug(message); } } **Key Differences:** - Inheritance shares behavior; interfaces enforce a contract. - A class can extend only one class but implement multiple interfaces. - Interfaces support loose coupling and are heavily used in Salesforce patterns like Trigger Handlers and Batch Apex (Database.Batchable). **Relevance to Process Automation:** Salesforce leverages interfaces extensively. For instance, Database.Batchable, Schedulable, and Queueable are standard interfaces used in asynchronous processing. Implementing these interfaces enables developers to build scalable automation solutions. Understanding inheritance and interfaces is critical for writing maintainable, extensible Apex code and is a core topic on the Platform Developer I certification exam.
Apex Interfaces and Inheritance: A Complete Guide for Salesforce Platform Developer 1
Why Apex Interfaces and Inheritance Matter
Apex Interfaces and Inheritance are foundational concepts in object-oriented programming (OOP) on the Salesforce platform. They allow developers to write modular, reusable, and maintainable code. Understanding these concepts is critical for the Salesforce Platform Developer 1 exam because they appear in questions related to process automation, trigger frameworks, design patterns, and the use of standard Salesforce interfaces such as Schedulable, Batchable, and Queueable. Without a solid grasp of interfaces and inheritance, you will struggle with questions on polymorphism, method overriding, and implementing platform-specific contracts.
What Are Apex Interfaces?
An interface in Apex is a contract that defines a set of method signatures without providing any implementation. Any class that implements an interface must provide concrete implementations for all the methods defined in that interface.
Syntax:
public interface MyInterface {
void doSomething();
String getResult(Integer num);
}
Key Characteristics of Interfaces:
- Interfaces define what a class must do, not how it does it.
- Methods in an interface have no body — they are abstract by default.
- Interfaces cannot contain instance variables or method implementations.
- A class can implement multiple interfaces (unlike inheritance, which is single in Apex).
- Interfaces enable polymorphism: you can reference different implementing classes through the same interface type.
Example of Implementing an Interface:
public class MyClass implements MyInterface {
public void doSomething() {
System.debug('Doing something');
}
public String getResult(Integer num) {
return 'Result: ' + num;
}
}
Standard Salesforce Interfaces You Must Know:
- Database.Batchable<SObject> — requires start(), execute(), and finish() methods for batch processing.
- Schedulable — requires the execute(SchedulableContext sc) method to schedule Apex jobs.
- Queueable — requires the execute(QueueableContext context) method for asynchronous processing.
- Comparable — requires the compareTo(Object obj) method for custom sorting.
- Iterable<SObject> — used with Batch Apex for custom iterators.
- Database.Stateful — a marker interface (no methods) that tells Batch Apex to maintain state across execute() calls.
- Database.AllowsCallouts — a marker interface that permits HTTP callouts in batch execution.
What Is Apex Inheritance?
Inheritance allows one class (the child or subclass) to inherit the properties and methods of another class (the parent or superclass). This promotes code reuse and establishes an is-a relationship between classes.
Syntax:
public virtual class Animal {
public virtual String speak() {
return 'Some sound';
}
}
public class Dog extends Animal {
public override String speak() {
return 'Woof!';
}
}
Key Keywords for Inheritance:
- virtual — Allows a class to be extended or a method to be overridden by child classes.
- extends — Used by a child class to inherit from a parent class.
- override — Used in the child class to provide a new implementation of a virtual or abstract method from the parent.
- abstract — Defines a class that cannot be instantiated directly, or a method that has no implementation and must be overridden by subclasses.
- super — Used to call the parent class constructor or methods from the child class.
Important Rules of Inheritance in Apex:
- Apex supports single inheritance only — a class can extend only one parent class.
- A class can extend one class and implement multiple interfaces simultaneously.
- You can only override methods that are declared as virtual or abstract in the parent class.
- Constructors are not inherited. If the parent class has a parameterized constructor and no no-arg constructor, the child must explicitly call super() with appropriate arguments.
- The super keyword is used to invoke the parent's constructor: super(param1, param2);
Abstract Classes vs. Interfaces — Key Differences:
| Feature | Abstract Class | Interface |
An abstract class can contain both implemented methods and abstract (unimplemented) methods. It can also have member variables. A class extends an abstract class.
An interface can only contain method signatures with no implementation and no member variables. A class implements an interface.
A class can extend only one abstract class but can implement multiple interfaces.
Use abstract classes when you want to share common code among closely related classes. Use interfaces when you want to define a capability that can be adopted by unrelated classes.
How It All Works Together — Polymorphism:
Polymorphism means you can treat objects of different classes through a common interface or parent class type. This is extremely powerful for writing flexible and extensible code.
Example with Interface Polymorphism:
public interface Discountable {
Decimal getDiscount();
}
public class PremiumCustomer implements Discountable {
public Decimal getDiscount() { return 0.20; }
}
public class RegularCustomer implements Discountable {
public Decimal getDiscount() { return 0.05; }
}
// Usage:
Discountable customer = new PremiumCustomer();
System.debug(customer.getDiscount()); // 0.20
customer = new RegularCustomer();
System.debug(customer.getDiscount()); // 0.05
The variable customer is declared as the interface type Discountable, but it can hold any implementing class. The correct method is called at runtime based on the actual object type. This is runtime polymorphism.
Example with Inheritance Polymorphism:
Animal myPet = new Dog();
System.debug(myPet.speak()); // Outputs 'Woof!' — Dog's overridden method is called
Practical Exam Scenarios:
1. Trigger Handler Frameworks:
Many best-practice trigger frameworks use interfaces. For example:
public interface ITriggerHandler {
void beforeInsert(List<SObject> newRecords);
void afterUpdate(Map<Id, SObject> oldMap, Map<Id, SObject> newMap);
}
Each object's handler class implements this interface, ensuring consistent structure across all triggers.
2. Batch Apex:
public class MyBatch implements Database.Batchable<SObject>, Database.Stateful {
// Must implement start(), execute(), finish()
}
3. Scheduled Apex:
public class MyScheduled implements Schedulable {
public void execute(SchedulableContext sc) {
// logic here
}
}
4. Using super keyword:
public virtual class BaseHandler {
public virtual void process() {
System.debug('Base processing');
}
}
public class AccountHandler extends BaseHandler {
public override void process() {
super.process(); // Calls parent's process first
System.debug('Account-specific processing');
}
}
============================================
Exam Tips: Answering Questions on Apex Interfaces and Inheritance
============================================
Tip 1: Know the keywords cold.
When a question mentions virtual, abstract, override, extends, implements, or super, immediately identify the OOP concept being tested. If you see extends — it's inheritance. If you see implements — it's an interface. A method with override must have a matching virtual or abstract method in the parent.
Tip 2: Remember single inheritance, multiple interface implementation.
A very common exam trap: a class can extend only ONE class but can implement MULTIPLE interfaces. If an answer option shows a class extending two classes, it is always wrong.
Tip 3: Abstract classes cannot be instantiated.
If a question shows code like: Animal a = new Animal(); and Animal is declared as abstract, this will cause a compile-time error. You can only instantiate concrete (non-abstract) subclasses.
Tip 4: All interface methods must be implemented.
If a class implements an interface but fails to provide an implementation for even one method, the code will not compile. This is a common trick in exam questions where one method is intentionally left out.
Tip 5: Understand marker interfaces.
Some Salesforce interfaces like Database.Stateful and Database.AllowsCallouts have no methods. They are marker interfaces that simply signal behavior to the platform. If a question asks how to maintain state in Batch Apex, the answer is Database.Stateful.
Tip 6: Watch for access modifiers.
Methods that override a parent method must have the same or broader access level. If the parent method is public virtual, the child's override must also be at least public. Also, interface methods are implicitly public, so implementing methods must be declared public.
Tip 7: The super keyword is only for parent class calls.
The super keyword is used to call a parent class constructor or method. It does NOT apply to interfaces. If a question uses super in the context of an interface, that answer is incorrect.
Tip 8: Look for compile errors vs. runtime errors.
Missing override keyword? Compile error. Implementing an interface but missing a method? Compile error. Instantiating an abstract class? Compile error. These are common question patterns where you need to identify what happens when the code runs.
Tip 9: Understand polymorphic variable assignment.
A parent class variable can hold a child class object. An interface variable can hold any implementing class object. The method that executes is determined at runtime based on the actual object type, not the variable type. This is frequently tested.
Tip 10: Know common Salesforce interfaces by their required methods.
- Schedulable → execute(SchedulableContext)
- Database.Batchable → start(), execute(), finish()
- Queueable → execute(QueueableContext)
- Comparable → compareTo(Object)
If a question asks which interface to implement for a given scenario, match the scenario to the correct interface and its methods.
Tip 11: Distinguish between abstract and virtual.
A virtual method has a default implementation that can be overridden. An abstract method has no implementation and must be overridden. A virtual class can be instantiated; an abstract class cannot.
Tip 12: Practice reading code snippets carefully.
Many exam questions present code blocks and ask what happens. Read the class declarations first: Is it abstract? Virtual? Does it implement an interface? Does it extend another class? Then check: Are all required methods implemented? Are the keywords (virtual, override) used correctly? This systematic approach will help you quickly identify the correct answer.
Summary:
Interfaces define contracts that classes must fulfill. Inheritance allows classes to reuse and extend behavior from parent classes. Together, they enable polymorphism, clean architecture, and adherence to Salesforce platform patterns. For the PD1 exam, focus on the keywords, rules (single inheritance, multiple interfaces), standard Salesforce interfaces, and common compile-time error scenarios. Master these, and you will confidently handle any question on this topic.
🎓 Unlock Premium Access
Salesforce Certified Platform Developer I + ALL Certifications
- 🎓 Access to ALL Certifications: Study for any certification on our platform with one subscription
- 2750 Superior-grade Salesforce Certified Platform Developer I practice questions
- Unlimited practice tests across all certifications
- Detailed explanations for every question
- PD1: 5 full exams plus all other certification exams
- 100% Satisfaction Guaranteed: Full refund if unsatisfied
- Risk-Free: 7-day free trial with all premium features!