default, static and private methods in interfaces
40 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)So far every interface method had no body. Since Java 8 and 9, an interface may also hold three kinds of method with a body: default, static and private. Each one solves a different problem.
The problem: adding a method breaks every class
A payment app has an interface Payment with pay, and 20 classes implement it. Now every payment must also print a receipt. Adding an abstract printReceipt breaks all 20 classes at once.
interface Payment { void pay(int amount); void printReceipt(int amount); // the new abstract method}
class UpiPayment implements Payment { public void pay(int amount) { System.out.println("Paid Rs. " + amount + " by UPI"); }}// error: UpiPayment is not abstract and does not override// abstract method printReceipt(int) in PaymentEvery class that signed the old contract now breaks the new one, as in Interfaces: a contract (opens in a new tab). Java 8 solved this with default methods. Java used them itself to add new methods to its own interfaces without breaking millions of programs.
Default methods
A default method is an interface method that has a body and is marked default. Every implementing class inherits it and may override it. It lets an interface get new methods without breaking the classes that already implement it.
Write default void printReceipt(int amount) { ... } inside Payment, with a body. The 20 old classes compile unchanged and simply inherit it, and any class may write its own version.
Example 1 · A default method: old classes get it for free
interface Payment { void pay(int amount);
default void printReceipt(int amount) { System.out.println("Receipt: Rs. " + amount + " paid"); }}
class UpiPayment implements Payment { public void pay(int amount) { System.out.println("UPI: Rs. " + amount); }}
class CardPayment implements Payment { public void pay(int amount) { System.out.println("Card: Rs. " + amount); }}
public class DefaultDemo { public static void main(String[] args) { Payment[] list = { new UpiPayment(), new CardPayment() }; for (Payment p : list) { p.pay(500); p.printReceipt(500); } }}UPI: Rs. 500 Receipt: Rs. 500 paid Card: Rs. 500 Receipt: Rs. 500 paid
What this code does
- Neither class mentions
printReceipt, yet both can call it. They inherit the default body from the interface. - If
printReceiptwere added as an abstract method instead, both classes would stop compiling.
Example 2 · A default that calls an abstract method, and an override
interface Payment { String method();
default void printReceipt(int amount) { System.out.println(method() + " receipt: Rs. " + amount); }}
class UpiPayment implements Payment { public String method() { return "UPI"; }}
class CardPayment implements Payment { public String method() { return "Card"; }
@Override public void printReceipt(int amount) { Payment.super.printReceipt(amount); System.out.println("Card fee: Rs. 10"); }}
public class OverrideDefaultDemo { public static void main(String[] args) { new UpiPayment().printReceipt(300); new CardPayment().printReceipt(300); }}UPI receipt: Rs. 300 Card receipt: Rs. 300 Card fee: Rs. 10
What this code does
- The default body calls
method(), and each object supplies its own name. CardPaymentoverrides the default aspublic, andPayment.super.printReceipt(amount)runs the interface version first.
A default method is always public, so an override must be public too. It can call the interface's abstract methods, and the object's own version runs, like the template idea from Constructors, fields and normal methods in abstract classes (opens in a new tab). Inside an override, Payment.super.printReceipt(amount) runs the interface's version, like super.method() with classes. A default still has no fields to use: an interface has only constants.
Two interfaces, same default: the class must decide
With bodies, the clash from Implement several interfaces (opens in a new tab) comes back. If Phone and Camera both have default void start(), a class implementing both gets two bodies, and javac refuses to guess.
Example 3 · Mistake: two interfaces with the same default
interface Phone { default void start() { System.out.println("Opening dialer"); }}
interface Camera { default void start() { System.out.println("Opening lens"); }}
class SmartPhone implements Phone, Camera {}
public class ConflictDemo { public static void main(String[] args) { new SmartPhone().start(); }}ConflictDemo.java:13: error: types Phone and Camera are incompatible;
class SmartPhone implements Phone, Camera {
^
class SmartPhone inherits unrelated defaults for start() from types Phone and Camera
1 errorWhat this code does
- The class gets two different
startbodies and Java will not guess which one you meant. - The message names the method and both interfaces, so you know exactly what to resolve.
Example 4 · The fix: override and choose with Interface.super
interface Phone { default void start() { System.out.println("Opening dialer"); }}
interface Camera { default void start() { System.out.println("Opening lens"); }}
class SmartPhone implements Phone, Camera { @Override public void start() { System.out.println("Phone booting"); Phone.super.start(); Camera.super.start(); }}
public class ConflictFixDemo { public static void main(String[] args) { new SmartPhone().start(); }}Phone booting Opening dialer Opening lens
What this code does
- Overriding
startin the class removes the doubt: the class version is the one that runs. Phone.super.start()andCamera.super.start()reuse each interface's body. You may call one, both or neither.
Java checks these rules in order:
- Class wins: a
publicmethod from a parent class beats any interface default. - More specific interface wins: if
SmartCamera extends Cameraand overridesstart(), a class implementing both gets theSmartCameraversion. - Otherwise you choose: override the method and call
Phone.super.start(),Camera.super.start(), both, or neither.X.superworks only for an interface the class lists afterimplements.
static methods in interfaces
A static interface method is a method with a body, marked static, that belongs to the interface itself. It is called with the interface name, as in Gst.withGst(500), and implementing classes do not inherit it.
Every bill needs the same GST sum, and that helper belongs with the contract, not with any one object. Write static int withGst(int amount) inside the interface Gst and call it as Gst.withGst(500).
Example 5 · static helper methods in an interface
interface Gst { int RATE = 18;
static int withGst(int amount) { return amount + amount * RATE / 100; }
static boolean isValid(int amount) { return amount > 0; }
int price();}
class Headphones implements Gst { public int price() { return 1500; }}
public class StaticDemo { public static void main(String[] args) { Gst item = new Headphones(); if (Gst.isValid(item.price())) { System.out.println("Price: Rs. " + item.price()); System.out.println("With GST: Rs. " + Gst.withGst(item.price())); } System.out.println("Valid -5? " + Gst.isValid(-5)); }}Price: Rs. 1500 With GST: Rs. 1770 Valid -5? false
What this code does
withGstandisValidbelong to the interface and are called asGst.withGst(...), never throughitem.Headphonesimplements only the abstractprice(). The static helpers are not inherited by it.
Unlike default methods, static methods are not inherited: Headphones.withGst(500) gives cannot find symbol, and item.withGst(500) gives illegal static interface method call. They cannot be overridden either. The four kinds side by side:
abstract: no body; every class must implement it.default: has a body; inherited; may be overridden.static: has a body; called asInterface.method(); not inherited.private: has a body; used only inside the interface.
private methods: shared code inside the interface
A private interface method is a method with a body, marked private, that only the interface's own methods can call. It holds code that several default methods share; implementing classes and outside code cannot use it.
printReceipt and printRefund both print the same kind of line. Copying those lines is risky, because a later change must be made twice. Since Java 9, one private method inside the interface holds them.
Example 6 · A private helper shared by two defaults
interface Payment { String method();
default void printReceipt(int amount) { printLine("Paid", amount); }
default void printRefund(int amount) { printLine("Refunded", amount); System.out.println("Money reaches your account in 3 days"); }
private void printLine(String action, int amount) { System.out.println(method() + " | " + action + ": Rs. " + amount); }}
class UpiPayment implements Payment { public String method() { return "UPI"; }}
class CardPayment implements Payment { public String method() { return "Card"; }}
public class PrivateHelperDemo { public static void main(String[] args) { Payment upi = new UpiPayment(); Payment card = new CardPayment(); upi.printReceipt(450); card.printReceipt(1200); card.printRefund(1200); }}UPI | Paid: Rs. 450 Card | Paid: Rs. 1200 Card | Refunded: Rs. 1200 Money reaches your account in 3 days
What this code does
- Both default methods use
printLine, so the receipt format is written once. Changing it changes every receipt. printLinecan callmethod(), so each object still prints its own name.printLineis not part of the contract:UpiPaymentdoes not inherit it, andupi.printLine(...)inmainwould not compile.
Outside code cannot call the helper: upi.printLine("Paid", 450) in main gives printLine(String,int) has private access in Payment. So the public contract stays small, just like a class with a private helper.
private static helper, because a static method has no object to work with.Next step
Check your understanding
12 quick questions