The Analogy: The Trade Cards In An Electrician's Wallet
Gita carries four laminated cards. One says she is registered under a domestic electrical scheme. One says she holds a first-aid-at-work certificate. One is a powered-access licence for scissor lifts. One is an abrasive-wheels ticket. Each card makes exactly one claim about what she is competent to do. Not one of them says a word about how she does it, where she trained, or who she works for. And there is no limit on how many she carries: the cards do not compete for the same slot in the wallet, so a fifth and a sixth can be added without any of the first four being touched.
The cards exist for a third party who will never meet the assessor. A site manager planning a shutdown needs to know that somebody on site can isolate a circuit and somebody on site is a first-aider. He writes those two requirements into the plan, checks two cards at the gate, and stops thinking about it. He does not ask which trade the holder is, and he certainly does not ask how the isolation is performed. He has planned the job against the claims on the cards rather than against the people holding them, which is why the plan survives Gita calling in sick and Omar turning up instead.
Turn a card over and you find things that belong to the scheme rather than to the holder. There is a standard procedure printed on the back, so that a holder with no employer-specific method still has something defensible to follow. There is the scheme's helpdesk number, which is the scheme's number and not Gita's -- ring it and you get the scheme, whoever's card you read it off. And there is an internal audit code that the scheme's own auditors use and the holder never quotes to anybody. Three different kinds of printing on one card: the claim, the fallback, and the scheme's own business.
Now the failure. The scheme widens its syllabus to include a new competency, and every card in every wallet is suddenly one competency short. Thousands of holders are non-compliant overnight without having done a single thing wrong. So the schemes learned to write new competencies as "follow the standard procedure on the back unless your employer specifies otherwise", which keeps every existing card valid on paper. It is a real solution to a real problem, and it has a real price: the scheme has now guaranteed that some holders are doing new work the generic way, and it has removed the moment where somebody would have had to sit down and learn the specific way. That bargain -- keep everybody compiling, at the cost of nobody being asked the question -- is precisely what a default method buys and precisely what it costs.
Syntax or Core Structure
An interface declares capabilities. A class claims as many as it likes with implements, separated by commas, and must supply a body for every abstract method it inherits.
interface Isolatable {
String LOCK_STANDARD = "LOTO-2019"; // implicitly public static final
void isolate(); // implicitly public abstract
default String certificate() { // a body, inherited by every implementer
return "generic isolation under " + LOCK_STANDARD;
}
static String helpdesk() { // belongs to the interface, not to implementers
return "0800-000-000";
}
}
interface Testable {
int reading();
default String verdict() { // written purely in terms of reading()
return reading() > 0 ? "live" : "dead";
}
}
class ChargePoint implements Isolatable, Testable {
private int volts = 230;
@Override public void isolate() { volts = 0; }
@Override public int reading() { return volts; }
@Override public String certificate() { // overrides the default
return "EV point isolated under " + LOCK_STANDARD;
}
}
class Lighting implements Isolatable, Testable {
private int volts = 230;
@Override public void isolate() { volts = 0; }
@Override public int reading() { return volts; }
// no certificate() override, so the interface's default is used
}
public class Wallet {
public static void main(String[] args) {
ChargePoint ev = new ChargePoint();
Lighting lt = new Lighting();
System.out.println("ev before " + ev.verdict());
ev.isolate();
System.out.println("ev after " + ev.verdict());
System.out.println("ev cert " + ev.certificate());
System.out.println("lt cert " + lt.certificate());
System.out.println("helpdesk " + Isolatable.helpdesk());
System.out.println("standard " + Isolatable.LOCK_STANDARD);
Isolatable any = lt; // held as the capability, not as the class
any.isolate();
System.out.println("lt after " + lt.verdict());
}
}
Output:
ev before live
ev after dead
ev cert EV point isolated under LOTO-2019
lt cert generic isolation under LOTO-2019
helpdesk 0800-000-000
standard LOTO-2019
lt after dead
Read the four moving parts off that output. verdict() is a body living in an interface that never sees a field: it works because it is written against reading(), and each class fills reading() in differently. certificate() shows the two halves of a default -- ChargePoint overrode it and got its own wording, Lighting said nothing and got the scheme's wording, and both compiled. helpdesk() had to be called as Isolatable.helpdesk() because a static interface method is not inherited; lt.helpdesk() would not compile. And the last two lines are the point of the whole construct: any is typed as a capability, the call went through without knowing there was a Lighting behind it, and the object it reached changed state.
Technical Depth: Everything An Interface Can Hold, How The Diamond Is Resolved, And What A Default Method Really Costs
The members an interface may declare
The one-line summary that interfaces "cannot have code" stopped being true in Java 8. What is still true is that they cannot have mutable state. Every field is a constant whether you say so or not.
| Member | Modifiers implied | Available since | Can an implementing class override it |
|---|---|---|---|
| Constant field | public static final | 1.0 | No -- a same-named class field hides it |
| Abstract method | public abstract | 1.0 | It must be implemented |
| Default method | public | 8 | Yes, optionally |
| Static method | public static | 8 | No -- it is not inherited at all |
| Private method | private | 9 | No -- invisible outside the interface |
| Private static method | private static | 9 | No |
| Nested type | public static | 1.1 | Not applicable |
Two consequences follow immediately. Because a field is final, an interface can never hold per-object data, so a default method has nothing to read except the results of the abstract methods -- that constraint is what makes verdict() work above. And because a field is static final and initialised with a compile-time constant, LOCK_STANDARD is inlined into every class that mentions it, exactly as described in the lesson on class attributes. Change the string in the interface and recompile the interface alone, and every implementer keeps printing the old value.
Where the line between an abstract class and an interface actually falls
The previous lesson left this table open deliberately. Here it is.
| Question | Abstract class | Interface |
|---|---|---|
| How many may one class take | Exactly one | Any number |
| Mutable instance state | Yes, fields of any kind | No, every field is public static final |
| Constructor | Yes, and every subclass must chain to it | No |
| Non-public members | protected and package-private allowed | Only public, plus private helpers used inside |
| Method bodies | Always | Since Java 8, via default and static |
| Can it forbid overriding | Yes, with final methods | No, a default method is always overridable |
| What it models | A partly built implementation | A capability a type claims |
The row that decides most real designs is the first one. A class has one superclass slot, and spending it is irreversible; implements costs nothing, and a class can add a capability years later without disturbing anything it already extends. So the working rule is: reach for an interface first, and reach for an abstract class only when you need to hold state or to make an order of operations final.
The diamond, and the three rules that resolve it
Because a class may implement several interfaces, it can inherit two bodies for one signature. Java does not pick for you.
interface Audited {
default String stamp() { return "audited"; }
}
interface Signed {
default String stamp() { return "signed"; }
}
class Certificate implements Audited, Signed {
@Override
public String stamp() {
return Audited.super.stamp() + "+" + Signed.super.stamp();
}
}
public class Diamond {
public static void main(String[] args) {
System.out.println("both " + new Certificate().stamp());
Audited a = new Certificate();
System.out.println("as audit " + a.stamp());
}
}
Output:
both audited+signed
as audit audited+signed
Delete the override and the class does not compile: the compiler reports that Certificate inherits unrelated defaults for stamp() from types Audited and Signed. It is a compile error at the class, not at the call, which is the good outcome -- the ambiguity is found by whoever created it. The Audited.super.stamp() form is the only syntax that reaches a specific inherited default, and it is legal only inside a class that directly implements that interface.
The resolution order is three rules applied in sequence. First, a body inherited from a superclass wins over any interface default, always. Second, if the two candidates are related by inheritance, the more specific interface wins -- if Signed extends Audited, then Signed's default is chosen with no error. Third, if neither rule settles it, the compiler refuses and you must write an override, even if all you do in that override is delegate.
Why "the class always wins" is the rule that made default safe to ship
Rule one above looks like a footnote. It is the whole reason default methods could be added to a language with twenty years of existing code.
interface Rated {
default int amps() { return 6; }
}
class Legacy {
public int amps() { return 32; }
}
class Modern extends Legacy implements Rated {
// declares nothing; inherits amps() from Legacy, not from Rated
}
public class ClassWins {
public static void main(String[] args) {
System.out.println("modern " + new Modern().amps());
Rated r = new Modern();
System.out.println("via iface " + r.amps());
}
}
Output:
modern 32
via iface 32
Modern inherits a concrete amps() from its superclass and a default amps() from its interface, and there is no ambiguity error and no need for an override: the superclass body wins outright. Both lines print 32, including the one that calls through the interface type, because dynamic dispatch always lands on the class's method. This is what let the JDK retrofit default methods onto Collection, List, Comparator and the rest without breaking a single existing implementation -- any class that already had a method of that name simply kept using it.
The rule cuts the other way too, and this is worth knowing before you rely on a default. If your own class already had amps() for unrelated reasons and later implements Rated, your method silently becomes the implementation of the interface's method. Nobody is warned. The signatures matched, so as far as the language is concerned that was your intent.
Functional interfaces, and what a lambda is not
An interface with exactly one abstract method is a functional interface and can be written as a lambda. Default methods, static methods, and re-declared public methods of Object do not count towards that total, which is why Comparator is functional despite declaring equals and carrying more than a dozen default and static methods. The @FunctionalInterface annotation changes no behaviour; it asks the compiler to fail the interface if somebody later adds a second abstract method, which is exactly the check you want on a published type.
A lambda is not shorthand for an anonymous class, and the difference shows up in ways you can observe. Inside an anonymous class this refers to the anonymous instance; inside a lambda this refers to the enclosing instance, so a lambda cannot accidentally shadow the outer object the way the nested-class lesson showed. A lambda has no supertype other than the functional interface it targets, cannot declare fields, and cannot be recursive by referring to itself.
What a default method costs
A default method is a body you have promised to every implementer forever. Four specific prices are worth pricing in before you write one.
It cannot read state, so it can only be expressed in terms of the interface's own abstract methods. A default that does not call any of them is almost always wrong: it is asserting something on behalf of classes it has never seen, which is the failure the Real World section below demonstrates.
It removes the compile error that would have made somebody think. Add an abstract method and every implementer breaks loudly at build time; add a default and every implementer silently acquires behaviour its author never reviewed. That is the trade the analogy's certification scheme made, and it is the right trade only when the generic answer is genuinely acceptable.
It can break a class that implements two of your interfaces. Adding default String stamp() to Audited when Signed already has one turns a compiling class into a diamond error, in a class you may not own and did not touch. Adding a default is a source-compatible change to one interface and a breaking change to the set.
It cannot override a method of Object. default String toString() in an interface is a compile error, as are equals and hashCode, because Object's versions would win under rule one anyway and the language forbids writing the dead code. If you want a shared toString, you need an abstract class.
Real World Example: A Permit Desk Where Capabilities Compose And One Default Method Quietly Certifies Everybody
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
interface Named {
String name();
}
interface Isolator {
String LOCK_STANDARD = "LOTO-2019";
int isolationLevel();
default String isolationNote() {
return "isolation L" + isolationLevel() + " under " + LOCK_STANDARD;
}
}
interface FirstAider {
int firstAidHours();
// The generous default. Look at what it does not consult.
default boolean firstAidCurrent() {
return true;
}
}
interface HeightWorker {
int maxMetres();
static int siteLimit() { // not inherited; callers must qualify it
return 12;
}
default boolean canReach(int metres) {
return metres <= maxMetres() && metres <= HeightWorker.siteLimit();
}
}
class Electrician implements Named, Isolator, FirstAider, HeightWorker {
private final String who;
private final int hours;
Electrician(String who, int hours) {
this.who = who;
this.hours = hours;
}
@Override public String name() { return who; }
@Override public int isolationLevel() { return 3; }
@Override public int firstAidHours() { return hours; }
@Override public int maxMetres() { return 8; }
@Override
public boolean firstAidCurrent() { // this class answered the question honestly
return hours >= 18;
}
}
class Labourer implements Named, FirstAider, HeightWorker {
private final String who;
private final int hours;
Labourer(String who, int hours) {
this.who = who;
this.hours = hours;
}
@Override public String name() { return who; }
@Override public int firstAidHours() { return hours; }
@Override public int maxMetres() { return 4; }
// no firstAidCurrent() override, so the interface answers on this class's behalf
}
public class PermitDesk {
private static final List<String> GRANTED = new ArrayList<>();
static String assess(Named who, int metres) {
boolean reach = (who instanceof HeightWorker)
&& ((HeightWorker) who).canReach(metres);
boolean aid = (who instanceof FirstAider)
&& ((FirstAider) who).firstAidCurrent();
int hours = (who instanceof FirstAider)
? ((FirstAider) who).firstAidHours()
: 0;
boolean grant = reach && aid;
if (grant) {
GRANTED.add(who.name());
}
return String.format(Locale.ROOT,
"%-8s hours %2d reach %-5s aid %-5s %s",
who.name(), hours, reach, aid, grant ? "GRANTED" : "REFUSED");
}
public static void main(String[] args) {
Electrician gita = new Electrician("Gita", 24);
Electrician omar = new Electrician("Omar", 6);
Labourer sam = new Labourer("Sam", 0);
System.out.println(assess(gita, 6));
System.out.println(assess(omar, 6));
System.out.println(assess(sam, 3));
System.out.println(assess(gita, 10));
System.out.println("granted " + GRANTED.size());
System.out.println("first " + GRANTED.get(0));
System.out.println("second " + GRANTED.get(1));
System.out.println("sam hours " + sam.firstAidHours());
System.out.println("note " + gita.isolationNote());
System.out.println("limit " + HeightWorker.siteLimit());
System.out.println("standard " + Isolator.LOCK_STANDARD);
}
}
Output:
Gita hours 24 reach true aid true GRANTED
Omar hours 6 reach true aid false REFUSED
Sam hours 0 reach true aid true GRANTED
Gita hours 24 reach false aid true REFUSED
granted 2
first Gita
second Sam
sam hours 0
note isolation L3 under LOTO-2019
limit 12
standard LOTO-2019
The shape of the design is right, and it is a shape only interfaces can produce. Electrician claims four capabilities, Labourer claims three, and neither spent its single extends slot to do it. The desk's assess method takes a Named, which is the smallest thing it genuinely needs, and asks about the rest by capability rather than by class. Nowhere in PermitDesk does the word Electrician appear except in main, so a fourth trade can be added tomorrow by writing a class and nothing else. That is the site manager checking cards at the gate instead of asking people what their job title is.
The three kinds of printing on the back of the card are all present and all doing different work. isolationNote() is a default written strictly in terms of isolationLevel(), so it composes correctly with any implementer -- it read L3 out of Electrician without the interface holding a field. siteLimit() is static, belongs to the interface, and had to be written HeightWorker.siteLimit() at both call sites, including the one inside canReach, because a static interface method is not inherited by anything. And canReach is the useful kind of default: real logic, expressed over the abstract method, that every implementer would otherwise have duplicated.
Then look at rows two and three, which are the reason this program exists. Omar has six hours of first-aid training and is refused. Sam has zero hours and is granted a permit. Sam's hours value is sitting right there in the output, and the desk had access to it -- the fourth line prints it. The difference is not the data; it is that Electrician overrode firstAidCurrent() and Labourer did not, so the interface answered on Labourer's behalf with a cheerful return true. The default made honesty a liability: the class that engaged with the question is the one whose people get turned away, and the class that ignored it sailed through. Worse, nobody will ever be told. There was no compile error, no warning, and no line in the output that says "answered by default" -- which is exactly the bargain the certification scheme struck when it printed a standard procedure on the back of every card.
The rest of the limits are worth naming plainly. firstAidCurrent() never calls firstAidHours(), which is the tell -- a default that consults none of its interface's abstract methods is asserting something it cannot know, and the right shape here was an abstract method with no default at all. LOCK_STANDARD is a compile-time String constant, so its value is baked into Electrician and into PermitDesk; revise the standard, recompile the interface alone, and both classes keep printing LOTO-2019. GRANTED is a mutable static list with no removal path, no expiry and no synchronisation, so two desks running at once will corrupt it and a permit is never revoked. assess resolves capabilities with instanceof and a cast, so the capabilities compose but the checker does not -- a fifth interface means editing the desk, and Isolator is currently not checked at all despite existing. And canReach collapses two different refusals into one false: too high for this worker and too high for this site are different conversations, and row four cannot tell you which one happened.
Common Mistakes
- Expecting an interface field to hold per-object data. Every field in an interface is
public static final whether you write those words or not. int volts = 230; inside an interface is one shared constant, not a field each implementer gets, and any attempt to assign it later is a compile error.
- Declaring a "constant" that is a mutable object. `List<String> TRADES = new
ArrayList<>(); in an interface is final only in the sense that the reference cannot be reseated. Every implementer, and anybody who can name the interface, can call add on it. Use List.of(...)` so the object itself refuses mutation.
- Calling a static interface method through an instance or an implementer. Static
interface methods are not inherited by implementing classes or by sub-interfaces, so lt.helpdesk() and Lighting.helpdesk() both fail to compile. Only Isolatable.helpdesk() works. This is deliberate: it keeps the static from colliding with an implementer's own static of the same name.
- Narrowing access on the implementing method. An interface method is
public, so
writing void isolate() without public in the implementing class produces "attempting to assign weaker access privileges; was public". Overriding never reduces visibility.
- Trying to write
defaultversions ofObjectmethods.default String toString(),
default boolean equals(Object o) and default int hashCode() are all compile errors in an interface. Object's implementations would win under the class-wins rule anyway, so the language forbids the dead code. Shared toString behaviour needs an abstract class.
- Expecting the compiler to resolve a diamond. Two unrelated interfaces supplying a body
for the same signature is an error at the implementing class, not a silent pick and not a left-to-right preference. You must override, even if the override only delegates with Audited.super.stamp().
- Writing a default method that consults none of the interface's abstract methods. A
default has no state to read, so if it does not call the abstract methods it is asserting something about classes it has never seen. firstAidCurrent() returning a bare true is the whole bug in the Real World program.
- Adding an abstract method to a published interface. Every existing implementer stops
compiling. That loud break is often the right outcome, but it is a breaking change and has to be planned; reaching for default to avoid it silently gives every implementer behaviour its author never reviewed.
- Using an interface when the order of operations is the policy. Every
defaultmethod
is overridable and an interface has no final methods, so an interface cannot make anyone follow a sequence. If the sequence is the rule you are enforcing, you need an abstract class with a final template method calling abstract steps.
Best Practices
- **Reach for an interface first, and for an abstract class only when you need mutable state
or a final order of operations.** implements costs nothing and can be added later; extends spends the one superclass slot a class will ever have.
- Keep each interface to one capability and compose them at the class.
Named,
Isolator, FirstAider and HeightWorker are more useful separately than a single SiteWorker would be, because callers can then ask for exactly the one they need.
- **Declare parameters, fields and return types at the narrowest interface the code actually
uses.** assess(Named who, ...) can be handed any future trade; assess(Electrician who, ...) could not, and nothing in the body needed the extra capability.
- **Leave a method abstract unless the generic answer is genuinely correct for every
implementer you will never meet.** A default is a permanent promise, and its main effect is to delete the compile error that would have made somebody think about the question.
- **Write every default method purely in terms of the interface's own abstract methods, and
document that it is a default.** canReach and isolationNote are safe defaults precisely because their answers are derived from maxMetres() and isolationLevel().
- Put
@Overrideon every method that implements an interface method. It catches a
misspelled name or a wrong parameter type at once, and it is the only thing that distinguishes overriding a default from coincidentally having a method of the same name.
- **Never expose a mutable object through an interface constant, and prefer a static method
to a constant that might change.** List.of(...) makes the collection immutable, and a static accessor is read at run time instead of being inlined at compile time.
- **Annotate intended lambda targets with
@FunctionalInterface, and treat adding an
abstract method to a published interface as a breaking change.** The annotation makes the compiler defend the single-abstract-method property that lambda callers depend on.
Practice Exercises
- The Card That Answered For Everyone. Take the
PermitDeskprogram and delete the
default from FirstAider.firstAidCurrent(), leaving it abstract. Record which class now fails to compile and why, then implement it in Labourer as hours >= 6 and rerun. Predict the four permit rows before you run it, then write the version you would actually ship: a default that calls firstAidHours() and applies one honest threshold. Explain in two sentences which of the three versions you would publish and what each one costs the people implementing your interface.
- The Ambiguous Stamp. Build
Audited,SignedandCertificatefrom the diamond
section, then delete the override and record the compiler's exact message. Now fix it four ways: delegate to Audited.super, combine both, declare interface Signed extends Audited, and add a concrete superclass with its own stamp(). Which two fixes need no override in Certificate at all, and which of the three resolution rules is each one relying on?
- The Constant That Would Not Change. Put
IsolatorandElectricianin separate files,
compile both, and run something that prints LOCK_STANDARD. Change the constant to "LOTO-2026", recompile the interface only, and run again without recompiling Electrician -- record what prints. Then replace the constant with a static String lockStandard() method, repeat the whole exercise, and explain the difference in terms of when each value is read. Note why keeping both types in one source file hides the effect entirely.