Interfaces: a contract
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)An abstract class is a parent for one family. Java has a second tool for abstraction that is not tied to any family: the interface, a list of methods that any class can promise to have.
A contract: what, not how
A contract in Java is a promise about which methods a class will have: their names, parameters and return types, with no word about how they work. Callers rely only on the contract, so any class that keeps it can be used.
Think of the USB-C standard. Any phone that follows it works with any USB-C charger, whoever made the phone. The standard says only what the socket must offer, not how the phone works inside.
A contract does the same for classes. It is abstraction from Why abstraction? (opens in a new tab) written down as a rule: the caller knows the what, each class decides the how, and javac checks that every class that signs the contract keeps it.
The interface keyword
An interface is a type that lists the methods a class promises to provide, usually without bodies. It is a contract: it says what a class can do, not how. It has no normal fields and no constructor, and it cannot be instantiated.
A smart-home app switches fans and lights on and off. interface Switchable lists the two methods, turnOn() and turnOff(), with no bodies. Each device class signs it with implements and writes its own.
Example 1 · The smallest interface
interface Switchable { void turnOn(); void turnOff();}
class Fan implements Switchable { public void turnOn() { System.out.println("Fan spinning"); }
public void turnOff() { System.out.println("Fan stopped"); }}
class Light implements Switchable { public void turnOn() { System.out.println("Light on"); }
public void turnOff() { System.out.println("Light off"); }}
public class SwitchDemo { public static void main(String[] args) { Switchable s1 = new Fan(); Switchable s2 = new Light(); s1.turnOn(); s2.turnOn(); s1.turnOff(); }}Fan spinning Light on Fan stopped
What this code does
Switchablelists two methods with no bodies. Each class signs the contract withimplementsand writes both.- The methods in the classes are
public, because interface methods arepublicby default.
implements: signing the contract
implements is the keyword a class uses to follow an interface, as in class Fan implements Switchable. The class must then write a public body for every method of the interface, or be declared abstract.
A UPI wallet signs the Account contract but writes only deposit(). javac refuses the whole class and names the method it is missing.
Example 2 · Mistake: a class misses one method
interface Account { void deposit(int amount); int balance();}
class UpiWallet implements Account { private int money;
public void deposit(int amount) { money = money + amount; }}
public class MissingMethodDemo { public static void main(String[] args) { Account a = new UpiWallet(); a.deposit(500); }}MissingMethodDemo.java:6: error: UpiWallet is not abstract and does not override abstract method balance() in Account
class UpiWallet implements Account {
^
1 errorWhat this code does
- Signing
implements Accountis a promise to write both methods.UpiWalletwrotedepositbut notbalance. - Fix: add
public int balance() { return money; }, or mark the classabstractif a child will write it.
This is the same rule as for abstract methods in Abstract classes and abstract methods (opens in a new tab): interface methods are abstract. An abstract class may implement an interface and leave some methods to its own children.
What javac adds for you
Inside an interface, void pay(int amount); really means public abstract void pay(int amount);, and int PASS_MARKS = 35; means public static final int PASS_MARKS = 35;. Both hidden words have effects.
Example 3 · Mistake: implementing without public
interface Payable { void pay(int amount);}
class UpiPayment implements Payable { void pay(int amount) { System.out.println("UPI: Rs. " + amount); }}
public class WeakerAccessDemo { public static void main(String[] args) { Payable p = new UpiPayment(); p.pay(250); }}WeakerAccessDemo.java:6: error: pay(int) in UpiPayment cannot implement pay(int) in Payable
void pay(int amount) {
^
attempting to assign weaker access privileges; was public
1 errorWhat this code does
- In the interface,
payispublic. In the class it has no access word, which is narrower thanpublic. - Fix: write
public void pay(int amount)inUpiPayment. This is the most common interface error.
Example 4 · Constants in an interface
interface Grading { int PASS_MARKS = 35; int MAX_MARKS = 100;
String grade(int marks);}
class SchoolGrading implements Grading { public String grade(int marks) { if (marks >= 90) { return "A"; } if (marks >= PASS_MARKS) { return "Pass"; } return "Fail"; }}
public class GradingDemo { public static void main(String[] args) { Grading g = new SchoolGrading(); System.out.println("Pass mark: " + Grading.PASS_MARKS + "/" + Grading.MAX_MARKS); System.out.println("92 -> " + g.grade(92)); System.out.println("40 -> " + g.grade(40)); System.out.println("20 -> " + g.grade(20)); }}Pass mark: 35/100 92 -> A 40 -> Pass 20 -> Fail
What this code does
PASS_MARKSandMAX_MARKSarepublic static finalwithout saying so.mainuses them through the interface name.- Inside
SchoolGrading, which implementsGrading, the plain namePASS_MARKSworks.
Example 5 · Mistake: changing a constant and using new
interface Grading { int PASS_MARKS = 35;
String grade(int marks);}
public class InterfaceRulesDemo { public static void main(String[] args) { Grading.PASS_MARKS = 40; Grading g = new Grading(); System.out.println(g.grade(50)); }}InterfaceRulesDemo.java:9: error: cannot assign a value to final variable PASS_MARKS
Grading.PASS_MARKS = 40;
^
InterfaceRulesDemo.java:10: error: Grading is abstract; cannot be instantiated
Grading g = new Grading();
^
2 errorsWhat this code does
- Interface fields are
final, soPASS_MARKScan never change. Use a different constant, or a field in a class. - An interface cannot be instantiated. Create an object of a class that implements it, like
new SchoolGrading().
The rules that follow:
- The class must write the method as
public void pay(...). Withoutpublicit would have weaker access than the contract, which Method overriding (opens in a new tab) forbids. - A field is a constant: it needs a value on the same line (
int count;gives= expected) and can never change. - With no normal fields, an interface holds no state and has no constructor.
- Interfaces can also have methods with a body: default, static and private methods (opens in a new tab).
An interface as a type
A wallet app pays a hostel fee, a phone bill and a library fine. The three classes have nothing in common, yet all can implement Payable, so one Payable[] array holds them and one method totals them.
Example 6 · Unrelated classes, one interface type
interface Payable { String label(); int amountDue();}
class HostelFee implements Payable { public String label() { return "Hostel fee"; } public int amountDue() { return 40000; }}
class PhoneBill implements Payable { int plan = 299; int extraData = 50;
public String label() { return "Phone bill"; } public int amountDue() { return plan + extraData; }}
class LibraryFine implements Payable { int lateDays = 6;
public String label() { return "Library fine"; } public int amountDue() { return lateDays * 2; }}
public class BillsDemo { static int total(Payable[] items) { int sum = 0; for (Payable p : items) { System.out.println(p.label() + ": Rs. " + p.amountDue()); sum = sum + p.amountDue(); } return sum; }
public static void main(String[] args) { Payable[] bills = { new HostelFee(), new PhoneBill(), new LibraryFine() }; System.out.println("Total: Rs. " + total(bills)); }}Hostel fee: Rs. 40000 Phone bill: Rs. 349 Library fine: Rs. 12 Total: Rs. 40361
What this code does
- The three classes share no parent, but all implement
Payable, so onePayable[]array holds them. totalknows only the contract. Each object works out its own amount, and a new kind of bill needs no change intotal.
You cannot write new Payable(), but you can use the interface as a variable, parameter or array type. Through a Payable reference you call only the interface's methods, and the object's own version runs. Unlike a parent class, the classes need not be related at all.
Next step
Check your understanding
11 quick questions