Skip to content
  • Interfaces · Java

Interfaces

LearnViaNotes @learnvianotes· 4 min read

An interface is a contract of methods a class promises to provide. A class can implement many interfaces — Java's answer to multiple inheritance.

What an interface can contain

MemberImplicit modifiersSince
Abstract methodpublic abstract1.0
Constant fieldpublic static final1.0
default method (has a body, inherited)public8
static method (called on the interface only)public8
private / private static helper method—9
Nested typespublic static1.0

Implementing several interfaces

Java
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        Duck duck = new Duck();
        List<Swimmer> swimmers = new ArrayList<>(List.of(duck, new Fish()));
        for (Swimmer s : swimmers) s.swim();
        Flyer f = duck;                     // a Duck is also a Flyer
        f.fly();
        System.out.println(Flyer.MAX_ALTITUDE);
        System.out.println(duck instanceof Swimmer && duck instanceof Flyer);
    }
}

interface Swimmer { void swim(); }
interface Flyer {
    int MAX_ALTITUDE = 10_000;              // public static final
    void fly();
}

class Duck implements Swimmer, Flyer {
    public void swim() { System.out.println("duck paddles"); }   // must be public
    public void fly()  { System.out.println("duck flies"); }
}

class Fish implements Swimmer {
    public void swim() { System.out.println("fish swims"); }
}
Output
duck paddles
fish swims
duck flies
10000
true

Default, static and private methods

Java
public class Main {
    public static void main(String[] args) {
        Greeter en = name -> "Hello, " + name;    // one abstract method → lambda works
        System.out.println(en.greet("Asha"));
        System.out.println(en.greetLoudly("Ravi"));      // default method
        System.out.println(Greeter.polite().greet("Meera"));   // static factory
    }
}

interface Greeter {
    String greet(String name);                  // abstract

    default String greetLoudly(String name) {   // inherited, can be overridden
        return shout(greet(name));
    }

    static Greeter polite() {                   // Greeter.polite(), not inherited by implementers
        return name -> "Good evening, " + name;
    }

    private String shout(String s) {            // helper shared by default methods
        return s.toUpperCase() + "!";
    }
}
Output
Hello, Asha
HELLO, RAVI!
Good evening, Meera

The diamond problem with default methods

If a class inherits the same default method from two interfaces, it must override it and may pick one with Interface.super.method(). Rules: (1) a class method always wins over an interface default; (2) a more specific sub-interface wins; (3) otherwise you must resolve it yourself.

Java
public class Main {
    public static void main(String[] args) {
        System.out.println(new Phone().start());
    }
}

interface Camera { default String start() { return "camera on"; } }
interface Radio  { default String start() { return "radio on"; } }

class Phone implements Camera, Radio {
    @Override public String start() {           // required: otherwise compile error
        return Camera.super.start() + " + " + Radio.super.start();
    }
}
Output
camera on + radio on
Java
interface Camera { default String start() { return "camera on"; } }
interface Radio  { default String start() { return "radio on"; } }
class Phone implements Camera, Radio { }
javac
Main.java:3: error: types Camera and Radio are incompatible;
class Phone implements Camera, Radio { }
^
  class Phone inherits unrelated defaults for start() from types Camera and Radio

Abstract class vs interface

Abstract classInterface
Instance state (fields)YesNo — only public static final constants
ConstructorsYesNo
Multiple inheritanceNo — extends one classYes — implements many
Method bodiesAnydefault, static, private only
Member accessAny modifierpublic (or private helpers)
RelationshipIS-A (shared identity)CAN-DO (capability)
Lambda targetNoYes, if exactly one abstract method (functional interface)

Marker and functional interfaces

Java
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.RandomAccess;

public class Main {
    static String strategy(List<?> list) {
        return list instanceof RandomAccess ? "index loop" : "iterator";
    }

    public static void main(String[] args) {
        System.out.println(strategy(new ArrayList<>()));
        System.out.println(strategy(new LinkedList<>()));
    }
}
Output
index loop
iterator

Why were default methods added in Java 8?

Can an interface have a constructor or instance fields?

Can an interface extend another interface? A class?

If a class and an interface both provide the same method, which wins?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report