Skip to lesson

Interfaces: a contract

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.

Syntax
interface Name {
returnType methodName(parameters);
}

Example 1 · The smallest interface

SwitchDemo.javaJava
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();    }}
Output
Fan spinning
Light on
Fan stopped

What this code does

  • Switchable lists two methods with no bodies. Each class signs the contract with implements and writes both.
  • The methods in the classes are public, because interface methods are public by 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

MissingMethodDemo.javaJava
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);    }}
Sample compiler output
MissingMethodDemo.java:6: error: UpiWallet is not abstract and does not override abstract method balance() in Account
class UpiWallet implements Account {
^
1 error

What this code does

  • Signing implements Account is a promise to write both methods. UpiWallet wrote deposit but not balance.
  • Fix: add public int balance() { return money; }, or mark the class abstract if 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

WeakerAccessDemo.javaJava
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);    }}
Sample compiler output
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 error

What this code does

  • In the interface, pay is public. In the class it has no access word, which is narrower than public.
  • Fix: write public void pay(int amount) in UpiPayment. This is the most common interface error.

Example 4 · Constants in an interface

GradingDemo.javaJava
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));    }}
Output
Pass mark: 35/100
92 -> A
40 -> Pass
20 -> Fail

What this code does

  • PASS_MARKS and MAX_MARKS are public static final without saying so. main uses them through the interface name.
  • Inside SchoolGrading, which implements Grading, the plain name PASS_MARKS works.

Example 5 · Mistake: changing a constant and using new

InterfaceRulesDemo.javaJava
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));    }}
Sample compiler output
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 errors

What this code does

  • Interface fields are final, so PASS_MARKS can 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:

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.

Class diagram. The interface Payable lists String label() and int amountDue(). Three unrelated classes, HostelFee, PhoneBill and LibraryFine, each implement Payable with their own amountDue(). A Payable[] array can hold all three.

Example 6 · Unrelated classes, one interface type

BillsDemo.javaJava
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));    }}
Output
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 one Payable[] array holds them.
  • total knows only the contract. Each object works out its own amount, and a new kind of bill needs no change in total.

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