Memra

Declaring & implementing interfaces

Interfaces define contracts — a class implements many; fields are constants.

What an interface is

An interface defines a contract — a set of methods any implementing class promises to provide — without dictating how. A class can implement many interfaces (unlike extends, which is single-inheritance only):

public interface Flyable {
    void fly();              // public abstract by default
    void land();
}

public interface Swimmable {
    void swim();
}

public class Duck implements Flyable, Swimmable {
    @Override public void fly()  { System.out.println("Duck flies"); }
    @Override public void land() { System.out.println("Duck lands"); }
    @Override public void swim() { System.out.println("Duck swims"); }
}

Default modifiers in interfaces:

| Member | Implicit modifier | |---|---| | Methods (pre-Java 8) | public abstract | | Fields | public static final |

Because interface fields are public static final by default, they are constants, not per-instance state:

public interface Limits {
    int MAX_SIZE = 100;        // same as: public static final int MAX_SIZE = 100;
}

Writing private or protected on an interface method is a compile error in the pre-Java 9 model (Java 9 added private methods — covered in the next lesson).

NORMAL ~/memra/learn/java-from-zero/declaring-and-implementing utf-8 LF