SyntaxPilot
Courses/Java/Lesson 21

Java · Lesson 21 of 51 · 11 min

Interfaces, default and static methods

queued

These are the notes for Java episode 21. Episode 20 ended with a duck: it is a Bird, so it extends Bird, but it also swims, and class Duck extends Bird, Swimmer gave error: '{' expected. Today you fix that with interfaces. You will see why a class can extend only one class, describe abilities as contracts with interface and implements, put unrelated classes (a duck and a drone) behind one type, learn the rules with their real errors ("attempting to assign weaker access privileges; was public", "cannot assign a value to static final variable"), grow an interface safely with default methods, settle the two-defaults clash with Flyer.super, use static interface methods, and decide between an abstract class and an interface. Every example was run with javac 21.

The problem: some things fly, some swim, a duck does both

A pond simulation has a duck (flies and swims), a drone (flies, but it's a machine, not a bird) and a fish (swims only). The task: make everything that can fly, fly, and everything that can swim, swim. We are grouping by what they can do, not by what they are.

The obvious attempt: two abstract parents

abstract class Bird {
    abstract void fly();
}

abstract class Swimmer {
    abstract void swim();
}

class Duck extends Bird, Swimmer {
    void fly() { System.out.println("Duck flies"); }
    void swim() { System.out.println("Duck swims"); }
}

public class Main {
    public static void main(String[] args) {
        Duck d = new Duck();
        d.fly();
        d.swim();
    }
}
Main.java:9: error: '{' expected
class Duck extends Bird, Swimmer {
                       ^
1 error

And a second problem: should Drone extends Bird? Then a drone is a bird and inherits everything birds have (feathers, laying eggs). Nonsense.

Why it went wrong

  • A Java class extends exactly one class. Two parents could both give the child a field or method body with the same name; Java avoids that problem (the "diamond problem") entirely for classes.
  • extends means is-a. Flying isn't a family: a duck, a drone and a plane all fly and are unrelated.
  • We need can-do: a list of abilities with no family tree.

Real-life example: the wall socket

A wall socket In Java
The socket's shape: three pins, fixed spacing interface Flyer: the methods you must have
A fan, a kettle, a charger: different things, same plug Duck, Drone implements Flyer: unrelated classes
A laptop with a USB-C port and an HDMI port implements Flyer, Swimmer: many interfaces
The socket doesn't care what brand you plug in Flyer f = new Drone(); f.fly();

interface and implements

interface Flyer { void fly(); }              // a contract: method headers, no bodies
class Duck implements Flyer, Swimmer { ... } // "I promise to provide these methods"
  • An interface is a named set of method signatures (a contract). A class that implements it promises to provide every one.
  • A class can implement many interfaces (comma-separated), because interfaces carry no instance fields and no constructors.
  • An interface is a type: Flyer f = new Drone(); works like upcasting to a parent class. You can't write new Flyer().
interface Flyer {
    void fly();
}

interface Swimmer {
    void swim();
}

class Duck implements Flyer, Swimmer {
    public void fly() {
        System.out.println("Duck flaps over the pond");
    }
    public void swim() {
        System.out.println("Duck paddles across");
    }
}

class Drone implements Flyer {
    public void fly() {
        System.out.println("Drone hums up to 50 m");
    }
}

class Fish implements Swimmer {
    public void swim() {
        System.out.println("Fish darts under the water");
    }
}

public class Main {
    public static void main(String[] args) {
        Flyer[] sky = { new Duck(), new Drone() };
        for (Flyer f : sky) {
            f.fly();
        }
        Swimmer[] pond = { new Duck(), new Fish() };
        for (Swimmer s : pond) {
            s.swim();
        }
    }
}
Duck flaps over the pond
Drone hums up to 50 m
Duck paddles across
Fish darts under the water

The duck sits in both groups; the drone never pretended to be a bird.

extends and implements together

A class can extend one class and implement interfaces: extends first, then implements.

abstract class Bird {
    String name;
    Bird(String name) { this.name = name; }
    abstract void fly();
}

interface Swimmer {
    void swim();
}

class Duck extends Bird implements Swimmer {
    Duck() { super("Duck"); }
    void fly() { System.out.println(name + " flies"); }
    public void swim() { System.out.println(name + " swims"); }
}

public class Main {
    public static void main(String[] args) {
        Duck d = new Duck();
        d.fly();
        d.swim();
        Swimmer s = d;
        Bird b = d;
        System.out.println(s instanceof Bird);
        System.out.println(b instanceof Swimmer);
    }
}
Duck flies
Duck swims
true
true

An interface can extend interfaces

interface Flyer { void fly(); }
interface Glider extends Flyer { void glide(); }
class PaperPlane implements Glider {
    public void fly() { System.out.println("Thrown up"); }
    public void glide() { System.out.println("Glides down"); }
}
public class Main {
    public static void main(String[] args) {
        Flyer f = new PaperPlane();
        f.fly();
        ((Glider) f).glide();
    }
}
Thrown up
Glides down

(An interface uses extends for other interfaces, and may extend several: interface A extends B, C.)

The rules (with the real errors)

In an interface Is automatically Consequence
A method without a body public abstract implementing classes must write it, and it must be public
A variable public static final a shared constant; must be initialised; can't be reassigned
No constructors new Flyer() is an error
interface Flyer {
    void fly();
}

class Drone implements Flyer {
    void fly() {
        System.out.println("Drone hums up");
    }
}

class Kite implements Flyer {
}

public class Main {
    public static void main(String[] args) {
        Flyer f = new Drone();
        f.fly();
    }
}
Main.java:6: error: fly() in Drone cannot implement fly() in Flyer
    void fly() {
         ^
  attempting to assign weaker access privileges; was public
Main.java:11: error: Kite is not abstract and does not override abstract method fly() in Flyer
class Kite implements Flyer {
^
2 errors

Constants:

interface Flyer {
    int MAX_HEIGHT = 120;
    void fly();
}
// Flyer.MAX_HEIGHT = 500;
// error: cannot assign a value to static final variable MAX_HEIGHT

Default methods: growing an interface without breaking classes

The next problem: Flyer is a success and many classes implement it. Now every flyer must land():

interface Flyer {
    void fly();
    void land();
}

class Duck implements Flyer {
    public void fly() { System.out.println("Duck flies"); }
}

class Drone implements Flyer {
    public void fly() { System.out.println("Drone flies"); }
}

public class Main {
    public static void main(String[] args) {
        Flyer[] sky = { new Duck(), new Drone() };
        for (Flyer f : sky) {
            f.fly();
            f.land();
        }
    }
}
Main.java:6: error: Duck is not abstract and does not override abstract method land() in Flyer
class Duck implements Flyer {
^
Main.java:10: error: Drone is not abstract and does not override abstract method land() in Flyer
class Drone implements Flyer {
^
2 errors

One new method broke every implementing class. Java's own interfaces (like List) are implemented by millions of classes, so Java 8 added default methods: interface methods with a body that implementing classes inherit unless they override them.

interface Flyer {
    void fly();
    default void land() {
        System.out.println("Lands gently");
    }
    static double kmh(double mps) {
        return mps * 3.6;
    }
}

class Duck implements Flyer {
    public void fly() { System.out.println("Duck flies"); }
}

class Drone implements Flyer {
    public void fly() { System.out.println("Drone flies"); }
    @Override public void land() {
        System.out.println("Drone lands on its pad");
    }
}

public class Main {
    public static void main(String[] args) {
        Flyer[] sky = { new Duck(), new Drone() };
        for (Flyer f : sky) {
            f.fly();
            f.land();
        }
        System.out.println(Flyer.kmh(10) + " km/h");
    }
}
Duck flies
Lands gently
Drone flies
Drone lands on its pad
36.0 km/h

This is how Java 8 added forEach and sort to old interfaces without breaking existing code.

Two defaults with the same name

interface Flyer {
    default void describe() {
        System.out.println("I can fly");
    }
}

interface Swimmer {
    default void describe() {
        System.out.println("I can swim");
    }
}

class Duck implements Flyer, Swimmer {
}

public class Main {
    public static void main(String[] args) {
        new Duck().describe();
    }
}
Main.java:13: error: types Flyer and Swimmer are incompatible;
class Duck implements Flyer, Swimmer {
^
  class Duck inherits unrelated defaults for describe() from types Flyer and Swimmer
1 error

The fix: the class overrides the method, and may call either default with InterfaceName.super.method():

class Duck implements Flyer, Swimmer {
    @Override
    public void describe() {
        Flyer.super.describe();
        Swimmer.super.describe();
        System.out.println("So I'm a duck");
    }
}
I can fly
I can swim
So I'm a duck

Static methods in an interface

Helpers that belong to the interface itself (not to objects). Call them only through the interface name; they are not inherited by implementing classes:

Flyer.kmh(10)   // 36.0
f.kmh(10)       // error: illegal static interface method call
                //   the receiver expression should be replaced with the type qualifier 'Flyer'
Duck.kmh(10)    // error: cannot find symbol

Since Java 9, interfaces may also have private methods, to share code between default methods:

interface Greeter {
    default void morning() { say("Good morning"); }
    default void night() { say("Good night"); }
    private void say(String m) { System.out.println(">> " + m); }
}
class G implements Greeter {}
public class Main { public static void main(String[] a) { new G().morning(); new G().night(); } }
>> Good morning
>> Good night

Abstract class vs interface

Abstract class Interface
Meaning is-a: a family of close relatives can-do: an ability shared by unrelated classes
How many per class one (extends) many (implements A, B)
Instance fields (state) yes no (only public static final constants)
Constructors yes no
Method kinds abstract and concrete, any access abstract (public), default, static, private
Method access any abstract and default methods are public
Use when children share real state and code (Shape with name) you describe a capability (Flyer, Payment, Comparable)

Rule of thumb: start with an interface for a capability; add an abstract class when several implementations share real state and code.

What you just invented

Problem Fix
A class can have only one parent interface: a contract of abilities, many per class
A drone is not a bird Drone implements Flyer: no family tree needed
Adding a method breaks every class default method with a body
Two defaults clash override, and pick with X.super.m()
Helpers that belong to the ability static interface methods

The next problem: print a duck with System.out.println(duck) and you get something like Duck@1b6d3586, not its name. And two ducks with the same name aren't equals. We never wrote toString or equals, so where do they come from? Episode 22: final and the Object class.

Common mistakes (and the real error messages)

Mistake Real message Why Fix
class Duck extends Bird, Swimmer error: '{' expected one parent class only extends Bird implements Swimmer
void fly() (no public) in an implementing class error: fly() in Drone cannot implement fly() in Flyer / attempting to assign weaker access privileges; was public interface methods are public public void fly()
Not writing a promised method error: Kite is not abstract and does not override abstract method fly() in Flyer signed the contract, skipped a method write every method (or make the class abstract)
new Flyer() error: Flyer is abstract; cannot be instantiated an interface is only a contract new Drone()
Flyer.MAX_HEIGHT = 500; error: cannot assign a value to static final variable MAX_HEIGHT interface fields are constants keep changing state in the class
Two interfaces with the same default error: types Flyer and Swimmer are incompatible; Java won't guess override it in the class
f.kmh(10) on a static interface method error: illegal static interface method call static methods belong to the interface Flyer.kmh(10)

Mini project: a payment counter

interface Payment {
    boolean pay(double amount);
    default void receipt(double amount) {
        System.out.printf("Paid Rs %.2f by %s%n", amount, name());
    }
    String name();
    static double withGst(double amount) { return amount * 1.18; }
}
class Upi implements Payment {
    public String name() { return "UPI"; }
    public boolean pay(double a) { return true; }
}
class Card implements Payment {
    public String name() { return "Card"; }
    public boolean pay(double a) { return a <= 50000; }
}
class Cash implements Payment {
    double inWallet;
    Cash(double w) { inWallet = w; }
    public String name() { return "Cash"; }
    public boolean pay(double a) { return a <= inWallet; }
}
public class Main {
    public static void main(String[] args) {
        double bill = Payment.withGst(500);
        Payment[] ways = { new Upi(), new Card(), new Cash(200) };
        for (Payment p : ways) {
            if (p.pay(bill)) p.receipt(bill);
            else System.out.println(p.name() + " failed");
        }
    }
}
Paid Rs 590.00 by UPI
Paid Rs 590.00 by Card
Cash failed

Practice

  1. Add a Plane that flies ("Plane takes off from runway 2") to a Flyer[] with a drone, without changing the loop.
  2. Give Swimmer a default dive() that prints "Dives a little"; override it in Fish.
  3. Can an interface have a constructor? Why or why not?
Solutions

1.

interface Flyer { void fly(); }
class Plane implements Flyer {
    public void fly() { System.out.println("Plane takes off from runway 2"); }
}
class Drone implements Flyer {
    public void fly() { System.out.println("Drone hums up to 50 m"); }
}
public class Main {
    public static void main(String[] args) {
        Flyer[] sky = { new Drone(), new Plane() };
        for (Flyer f : sky) f.fly();
    }
}
Drone hums up to 50 m
Plane takes off from runway 2

2.

interface Swimmer {
    void swim();
    default void dive() { System.out.println("Dives a little"); }
}
class Duck implements Swimmer {
    public void swim() { System.out.println("Duck paddles"); }
}
class Fish implements Swimmer {
    public void swim() { System.out.println("Fish darts"); }
    @Override public void dive() { System.out.println("Fish dives to the bottom"); }
}
public class Main {
    public static void main(String[] args) {
        Swimmer[] pond = { new Duck(), new Fish() };
        for (Swimmer s : pond) { s.swim(); s.dive(); }
    }
}
Duck paddles
Dives a little
Fish darts
Fish dives to the bottom

3. No. An interface has no instance fields to initialise and can't be instantiated, so there is nothing for a constructor to do.

Quick quiz

interface Greeter {
    default String hi() { return "Hello"; }
}
class Hindi implements Greeter {
    public String hi() { return "Namaste"; }
}
class English implements Greeter { }
// in main:
Greeter[] g = { new Hindi(), new English() };
for (Greeter x : g) System.out.print(x.hi() + " ");

A) Hello Hello B) Namaste Hello C) Namaste Namaste D) Compile error: English has no hi()

Answer

B. Hindi overrides the default; English writes nothing and gets the default. A default method has a body, so it's never a must-fill.

Interview questions

  1. What is an interface? A reference type that declares a contract (abstract methods, plus optional default, static and private methods and constants) that implementing classes must fulfil.
  2. Does Java support multiple inheritance? Not of classes (one extends), but a class can implement many interfaces (multiple inheritance of type).
  3. Why were default methods added? To add methods to existing interfaces (Java 8: forEach, stream, sort) without breaking every implementing class.
  4. What if two interfaces have the same default method? The class must override it; it can call a specific one with Flyer.super.describe().
  5. Are interface variables instance variables? No, they are implicitly public static final constants.
  6. Abstract class vs interface? Abstract class: is-a, one per class, can hold state and constructors. Interface: can-do, many per class, no instance state.
  7. Can an interface extend a class? No. It can extend other interfaces only.
  8. What is a marker interface? An interface with no methods that tags a class (e.g. Serializable). And a functional interface has exactly one abstract method; it powers lambdas (episode 36).

Glossary

Term Meaning Example
Interface A contract of methods a class promises to provide interface Flyer { void fly(); }
implements Declares that a class fulfils an interface class Drone implements Flyer
Contract The set of methods an implementer must provide fly()
is-a The relationship expressed by extends (a family) a Circle is a Shape
can-do The relationship expressed by an interface (an ability) a Drone can fly
Multiple inheritance Inheriting from more than one parent implements Flyer, Swimmer (interfaces only)
Diamond problem Ambiguity when two parents provide the same member two describe() defaults
Default method An interface method with a body, inherited unless overridden default void land()
Static interface method A helper called only via the interface name Flyer.kmh(10)
Private interface method A helper shared by default methods (Java 9+) private void say(...)
Constant A public static final value int MAX_HEIGHT = 120;
Access privileges How visible a member is (public > protected > package > private) an override can't be less visible
X.super.m() Calls interface X's default m() from an implementing class Flyer.super.describe()

Summary

  • A class extends one class, and extends means is-a.
  • An interface is a can-do contract; a class can implement many.
  • Interface methods are public abstract by default; fields are public static final.
  • Interfaces work as types: Flyer f = new Drone();.
  • Default methods let an interface grow without breaking classes; clashing defaults must be overridden (X.super.m() picks one).
  • Static interface methods are called as Flyer.kmh(10) and aren't inherited.
  • Abstract class for close relatives sharing state; interface for abilities across unrelated classes.
  • Next: why println(duck) prints Duck@... and two equal ducks aren't equal. Episode 22: final and the Object class.