What is an Interface in Apex?
Interface in Apex is a contract that lists method signatures without method bodies. A class uses the implements keyword to follow that contract and must provide an implementation for every method declared in the interface.
When you define an Apex interface, you are also defining a type. A variable can be declared with the interface type and can hold an object of any class that implements that interface. This is useful when different classes should be called through the same set of method names.
- An Apex interface declares behavior; an implementing class supplies the actual logic.
- An interface cannot be instantiated directly with
new. - A class can implement more than one interface, but an Apex class can extend only one class.
- Use
publicfor code used inside the same org or namespace, andglobalonly when the interface must be exposed outside the package or namespace.
Reference: Salesforce explains Apex classes and interfaces in the Apex Developer Guide.
Apex Interface Syntax with the implements Keyword
The basic syntax is to declare the interface first and then create one or more classes that implement it. The method name, return type, and parameters in the class must match the interface method signature.
public interface InterfaceName {
ReturnType methodName(ParameterType parameterName);
}
public class ClassName implements InterfaceName {
public ReturnType methodName(ParameterType parameterName) {
// method body
}
}
Example syntax for a simple interface:
public interface AccountNameFormatter {
String formatName(Account accountRecord);
}
public class UpperCaseAccountNameFormatter implements AccountNameFormatter {
public String formatName(Account accountRecord) {
if (accountRecord == null || String.isBlank(accountRecord.Name)) {
return 'Unnamed Account';
}
return accountRecord.Name.toUpperCase();
}
}
In this example, AccountNameFormatter declares the method. UpperCaseAccountNameFormatter implements the interface and provides the method body.
Using an Apex Interface as a Variable Type
An interface variable can point to an object of a class that implements that interface. This lets the calling code depend on the interface contract instead of depending on one specific class.
public interface DiscountPolicy {
Decimal apply(Decimal amount);
}
public class SeasonalDiscount implements DiscountPolicy {
public Decimal apply(Decimal amount) {
return amount * 0.90;
}
}
DiscountPolicy policy = new SeasonalDiscount();
Decimal finalAmount = policy.apply(100);
System.debug(finalAmount);
90.00
The variable policy is declared as DiscountPolicy, but the actual object is SeasonalDiscount. Later, another class can implement DiscountPolicy and the caller can use it through the same interface.
Why Interfaces are Used in Apex Classes
Interfaces are used in Apex when the code needs a common contract across multiple implementations. They are especially helpful in service classes, trigger handlers, testing patterns, managed packages, and Salesforce platform interfaces such as Queueable, Batchable, Schedulable, Iterator, and Iterable.
- Loose coupling: calling code can depend on the interface instead of a concrete class.
- Multiple implementations: separate classes can implement the same interface with different logic.
- Testing flexibility: test code can use a simple implementation of an interface to isolate business logic.
- Platform contracts: Salesforce uses interfaces to define required methods for asynchronous Apex and collection traversal.
Interface vs Abstract Class vs Virtual Class in Apex
An Apex interface is not the same as an abstract class or a virtual class. Choose based on whether you need only a contract or also need shared implementation.
| Apex type | What it provides | When to use it |
|---|---|---|
| Interface | Method signatures without method bodies | Use when unrelated classes must follow the same contract. |
| Abstract class | Can contain abstract methods and implemented methods | Use when subclasses need common base logic plus required methods. |
| Virtual class | Can contain methods that subclasses may override | Use when default behavior exists but child classes may customize it. |
A class can implement multiple interfaces. This is one reason interfaces are commonly used when Apex code needs more flexible design than single inheritance allows.
Original Interface in Apex Syntax Snippet from this Lesson
The following original snippet is kept unchanged. In new Apex code, use valid Apex type names and spellings such as String, and include a method body only in the implementing class.
Public interface Exam {
Account Show(Sting S);
}
All methods declared in an interface must be implemented by a class that uses that interface. Interface methods represent signatures; the actual logic belongs in the implementing class.
Original Apex Interface Implementation Example from this Lesson
The next older example is also preserved unchanged. A corrected Apex version would declare the interface separately, then declare the class separately with all required methods implemented.
interface test {
public String Show()
void disp();
global Class Example implements test {
return 'Prasaanth';
}
public void disp( ) {
Account a = new Account(Name='Prasanth');
}
}
A corrected structure for the same idea is shown below.
public interface TestInterface {
String show();
void displayAccount();
}
public class Example implements TestInterface {
public String show() {
return 'Prasanth';
}
public void displayAccount() {
Account accountRecord = new Account(Name = 'Prasanth');
System.debug(accountRecord.Name);
}
}
Creating Objects with Apex Interfaces
You cannot create an object directly from an interface. You can create an object of a class that implements the interface, and then assign that object to an interface variable.
Class Test { }
Test t = new Test( );
interface Demo {
void Show ( );
}
- Demo d = new Demo(); is not allowed because an interface cannot be instantiated directly.
- Demo d = e; is allowed when
eis an object of a class that implements theDemointerface. - Demo d = t; is not allowed when the
Testclass does not implement theDemointerface.
A cleaner version of the same rule is shown below.
public interface Demo {
void show();
}
public class DemoImplementation implements Demo {
public void show() {
System.debug('Implemented show method');
}
}
Demo demoReference = new DemoImplementation(); // allowed
demoReference.show();
Interface Iterator in Apex Collections
Iterator is a Salesforce-defined Apex interface used to move through a collection one item at a time. It is commonly used with Iterable when you want a class to support controlled traversal.
Apex Iterator hasNext() Method
Boolean hasNext() returns true when another item is available in the collection. It returns false when the iterator has reached the end.
Apex Iterator next() Method
AnyType next() returns the next item in the collection. When using a typed iterator such as Iterator<Account>, the method returns an Account.
How to Create a Custom Iterator in Apex
The original custom iterator snippet is preserved below. After it, a corrected version is provided for practical use.
public class Prasanth implements Iterator <Account> {
public List <Account> acc;
public Integer i;
public Prasanth( ) {
acc = [SELECT name FROM Account];
i = 0;
}
public boolean hasNext () {
if(i>acc.size())
return false;
else
return true;
}
Public Account next() {
if(i==o)
return null;
i++;
return a[i-1];
}
}
A custom iterator should track its current position and should not read beyond the end of the list.
public class AccountIterator implements Iterator<Account> {
private List<Account> accounts;
private Integer index = 0;
public AccountIterator(List<Account> accounts) {
this.accounts = accounts == null ? new List<Account>() : accounts;
}
public Boolean hasNext() {
return index < accounts.size();
}
public Account next() {
if (!hasNext()) {
return null;
}
Account currentAccount = accounts[index];
index++;
return currentAccount;
}
}
Interface Iterable in Apex
Iterable is an Apex interface that returns an Iterator. If a class implements Iterable<Account>, it must define an iterator() method that returns Iterator<Account>.
The original iterable example is kept unchanged below.
class Bened implements Iterable<Account> {
public Iterator<Account> iterator() {
Prasanth P = new Prasanth();
Iterator<Account> it = s;
return it;
}
}
A corrected iterable class can return the custom iterator created above.
public class AccountIterable implements Iterable<Account> {
private List<Account> accounts;
public AccountIterable() {
accounts = [
SELECT Id, Name
FROM Account
ORDER BY Name
LIMIT 50
];
}
public Iterator<Account> iterator() {
return new AccountIterator(accounts);
}
}
You can use the iterable class in a loop.
for (Account accountRecord : new AccountIterable()) {
System.debug(accountRecord.Name);
}
Visualforce Controller Example Using an Apex Iterable
The following controller snippet from the original lesson is kept unchanged. In production code, make sure the iterable class name exists, the while condition is valid, and the action method returns a valid PageReference or null.
public class SampleIterator {
public List <Account> acc;
public List <Account> getAcc() {
return acc;
}
public SampleIterator() {
acc = new List <Account>();
}
public pageReference Show() {
Iterable <Account> my = new tkartiterable();
Iterator <Account> test = my.Iterator();
while(test.next()!-null) {
Account a = test.next();
acc.add(a);
}
}
}
Visualforce Page for Displaying Accounts from the Iterator
<apex:page controller="SampleIterator">
<apex:form>
<apex:commandButton value="click" action="{!show}"/>
<apex:pageBlock>
<apex:pageBlockTable value="{!acc}" var="a">
<apex:column value="{!a}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>
Common Apex Interface Mistakes to Avoid
- Trying to instantiate an interface: use
new ImplementingClass(), notnew InterfaceName(). - Changing the method signature: the implementing method must match the interface return type, method name, and parameters.
- Forgetting one method: a class that implements an interface must implement every method in that interface.
- Using an interface when shared logic is required: if the base type must contain reusable code, consider an abstract or virtual class instead.
- Calling next() twice in a loop condition: store the value returned by
next()when the loop needs to use that same item.
Interface in Apex FAQs
What is an interface used for in Apex?
An interface in Apex is used to define a common set of method signatures that one or more classes must implement. It helps different classes follow the same contract while keeping their implementation logic separate.
Can an Apex interface contain method bodies?
No. An Apex interface contains method declarations, not method bodies. The class that implements the interface provides the body for each method.
Can a class implement multiple interfaces in Apex?
Yes. An Apex class can implement multiple interfaces by separating the interface names with commas after the implements keyword.
Can we create an object of an interface in Apex?
No. You cannot instantiate an interface directly. You can instantiate a class that implements the interface and assign that object to a variable declared with the interface type.
When should I use an interface instead of an abstract class in Apex?
Use an interface when you only need a contract and may have unrelated classes implementing it. Use an abstract class when subclasses need shared code, shared state, or default behavior.
Apex Interface Editorial QA Checklist
- Verify every implementing class defines all interface methods with matching names, parameters, and return types.
- Confirm examples do not instantiate an interface directly.
- Check whether
publicorglobalis appropriate for the intended visibility. - For
Iteratorexamples, confirmhasNext()usesindex < list.size()andnext()does not skip records. - Run new Apex examples in an org or scratch org before publishing if the page is used as a copy-paste coding tutorial.
TutorialKart.com