Java 接口

接口的声明与实现、多接口、default/static 方法与接口继承。

Intermediate
Key Points接口方法隐式 public abstract,字段隐式 public static final;Java 8 起支持 default 与 static 方法。

接口的声明

interface declares a capability contract. Methods are implicitly public abstract and fields public static final — writing those modifiers is redundant and often rejected.

Java
interface Animal {
    int MAX_AGE = 100;          // public static final

    void eat();                 // public abstract
}

class Dog implements Animal {
    @Override
    public void eat() {
        System.out.println("dog eats");
    }
}

public class InterfaceDemo {
    public static void main(String[] args) {
        Animal a = new Dog();
        a.eat();
        System.out.println(Animal.MAX_AGE);
    }
}
Output
dog eats
100

接口的实现

A class implements with implements and must define every abstract method as public — the interface declares them public, so narrowing is illegal.

Java
interface Flyer {
    void fly();
}

interface Swimmer {
    void swim();
}

class Duck implements Flyer, Swimmer {
    @Override
    public void fly() {
        System.out.println("duck flies");
    }

    @Override
    public void swim() {
        System.out.println("duck swims");
    }
}

public class MultiImpl {
    public static void main(String[] args) {
        Duck d = new Duck();
        d.fly();
        d.swim();

        Flyer f = d;
        f.fly();
    }
}
Output
duck flies
duck swims
duck flies

default 与 static 方法

Since Java 8 an interface may hold default methods (implemented, overridable) and static methods (callable only via the interface name). This lets interfaces evolve without breaking implementations.

Java
interface Greeter {
    void greet();

    default void greetTwice() {
        greet();
        greet();
    }

    static Greeter of(String name) {
        return () -> System.out.println("hi " + name);
    }
}

public class DefaultDemo {
    public static void main(String[] args) {
        Greeter g = Greeter.of("Tom");
        g.greetTwice();
    }
}
Output
hi Tom
hi Tom

接口的继承

Interfaces extend with extends and may extend several at once. A child interface inherits abstract and default methods, and implementing classes must fulfil all abstract ones.

Java
interface A {
    void a();
}

interface B extends A {
    void b();
}

class Impl implements B {
    @Override
    public void a() {
        System.out.println("a");
    }

    @Override
    public void b() {
        System.out.println("b");
    }
}

public class ExtendsInterface {
    public static void main(String[] args) {
        Impl i = new Impl();
        i.a();
        i.b();
        System.out.println(i instanceof A);
    }
}
Output
a
b
true

Friends & Partners