Sub topic 14
Inner classes and their restrictions
An inner class is a class declared inside another class. This chapter assumes you can already write top-level classes, use access modifiers, and tell static members from instance members. Inner classes are a small feature with several restrictions that surprise people, mostly because they differ from Java.
What an inner class is
A top-level class lives in its own file. An inner class is declared in the body of another class, called the outer class. The outer class must be a top-level class.
public class OrderSummary {
public class Line {
public String sku;
public Decimal total;
public Line(String sku, Decimal total) {
this.sku = sku;
this.total = total;
}
}
}Code outside OrderSummary refers to the inner class by its qualified name:
OrderSummary.Line first = new OrderSummary.Line('A-100', 25.50);
System.debug(first.sku); // A-100Code inside OrderSummary can use the short name Line.
Why use one
Inner classes are useful when a small type exists only to serve the outer class. Common cases are:
- Wrapper classes. A Visualforce or Lightning controller wraps a record with extra data, such as a
Boolean selectedflag next to anAccount. - Data transfer objects. A service returns a structured result instead of several parallel lists.
- Small strategy implementations. A private class implements an interface and is never used elsewhere.
- Test helpers. A test class defines a stub or mock next to the tests that use it.
The benefit is namespacing and encapsulation. The helper type does not clutter your org's list of classes, and a private inner class cannot be used by other code at all.
Restriction 1: only one level of nesting
An inner class cannot contain another inner class. The nesting stops at depth one.
The diagram below shows the allowed and disallowed shapes.
If you need a third level, move one of the types out to the top level or flatten the structure. Interfaces and enums can also be declared inside a class, but they follow the same one-level limit.
Restriction 2: no access to outer instance members
In Java, a non-static inner class holds a hidden reference to an instance of the outer class. Apex inner classes do not. They behave like Java's static nested classes, even though you never write static on them.
Two consequences follow:
- You can create an inner object without creating an outer object.
- Inner code cannot read or call the outer class's instance fields and methods, because there is no outer object to read them from.
public class Report {
private String title = 'Q3 Summary';
private static Integer rowsBuilt = 0;
public class Row {
public String label;
public Row(String label) {
this.label = label;
rowsBuilt++; // allowed: static member of the outer class
// System.debug(title); // compile error: title is an instance field
}
}
public static Integer getRowsBuilt() {
return rowsBuilt;
}
}
// Usage: no Report object exists
Report.Row r = new Report.Row('Revenue');
System.debug(Report.getRowsBuilt()); // 1An inner class can use the outer class's static members, including private ones. If an inner object needs outer instance data, pass it in through the constructor or a method parameter, as in this example:
public class Report {
private String title = 'Q3 Summary';
public class Row {
private final String reportTitle;
public String label;
public Row(String reportTitle, String label) {
this.reportTitle = reportTitle;
this.label = label;
}
public String fullName() {
return reportTitle + ': ' + label;
}
}
public Row newRow(String label) {
return new Row(this.title, label);
}
}This is the same pattern you would use between two top-level classes, which is why an inner class gives no special access to instance state.
Restriction 3: visibility rules
An inner class has an access modifier like any other class. If you omit it, the inner class is private to the outer class.
| Declaration | Who can use it |
|---|---|
| `private class Helper` or `class Helper` | Only code in the outer class |
| `public class Helper` | Any Apex code in the namespace, as `Outer.Helper` |
| `global class Helper` | Code in other namespaces, if the outer class is also `global` |
A private inner class is invisible to test classes. If you want to test it, mark it with @TestVisible:
public class PriceCalculator {
@TestVisible
private class Breakdown {
public Decimal base;
public Decimal tax;
}
}A common error is to forget the modifier, then see "Invalid type" in another class that tries to use Outer.Helper. The fix is to make the inner class public.
Inner classes can implement and extend
An inner class takes part in the same type system as other classes. It can implement an interface and extend a virtual or abstract class. An inner class that implements Comparable can be sorted with List.sort():
public class SalesRanking {
public class Entry implements Comparable {
public String rep;
public Decimal amount;
public Entry(String rep, Decimal amount) {
this.rep = rep;
this.amount = amount;
}
public Integer compareTo(Object other) {
Entry o = (Entry) other;
if (amount == o.amount) {
return 0;
}
return amount > o.amount ? 1 : -1;
}
}
public static List<Entry> rank(List<Entry> entries) {
entries.sort();
return entries;
}
}
// Usage
List<SalesRanking.Entry> list1 = new List<SalesRanking.Entry>{
new SalesRanking.Entry('Ana', 5000),
new SalesRanking.Entry('Bo', 3000)
};
SalesRanking.rank(list1);
System.debug(list1[0].rep); // BoAn inner class can also be the implementation of an inner interface. This keeps a small contract and its single implementation together in one file.
Other limits to remember
- Triggers cannot contain inner classes. Put the logic in a handler class and use inner classes there.
- One file holds the whole thing. The outer class and all its inner classes share one
.clsfile, which grows quickly. If an inner class passes about 50 lines or is used by several classes, make it a top-level class. - Equality is by reference by default. Two inner objects with the same field values are not equal unless you define
equalsandhashCode. This matters if you use inner objects asMapkeys or in aSet. - Names must differ from the outer class. An inner class cannot have the same name as its outer class.
Choosing between inner and top-level
| Question | If yes |
|---|---|
| Does only one class use this type? | Inner class |
| Is it a small data holder or wrapper? | Inner class |
| Do several classes share it? | Top-level class |
| Does it need more than one level of nesting? | Top-level class |
| Do you need to test it directly? | Top-level, or `@TestVisible` inner |
Exercise
A class Cart has an instance field private Decimal discount = 10; and an inner class Item with a method Decimal priceAfterDiscount(Decimal price) that tries to return price - discount. Why does this fail to compile, and how would you fix it?
Show answer
Apex inner classes have no reference to an outer instance, so Item cannot read the instance field discount. Fix it by passing the value in, for example through the Item constructor or as a method parameter, or by making discount a static field of Cart (only if it truly is shared by the whole class).
Exercise
You write public class A { public class B { public class C {} } }. What happens, and what are two ways to resolve it?
Show answer
It does not compile, because an inner class cannot contain another inner class. You can move C into A as a sibling of B, or promote B or C to its own top-level class.