Java 接口方法

#默认方法

  • 解决的问题:接口升级的问题。(从 Java 8 开始可以使用 default 关键字来定义默认方法)

因为接口的实现类要实现接口中所有的抽象方法,因此如果要在接口中添加一个新的方法,所有已经实现了该接口的类都会受到影响。使用 default 为接口添加方法时,任何实现接口却没有定义该方法的实现类可以使用 default 创建的方法体。(可以在实现类中直接使用,也可以在实现类中进行重写)它允许在不破坏已使用接口的代码的情况下,在接口中增加新的方法。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
interface InterfaceWithDefault {
	void firstMethod();
	void secondMethod();
	default void newMethod() {  // 可以在实现类中直接使用,也可以在实现类中进行重写
		System.out.println("newMethod");
	} 
}

public class Implementation implements InterfaceWithDefault {
    @Override
    public void firstMethod() {
        System.out.println("firstMethod");
    }

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

    public static void main(String[] args) {
        InterfaceWithDefault i = new Implementation();
        i.firstMethod();
        i.secondMethod();
        i.newMethod();  // 直接使用接口中的默认方法
    }
}
// 示例代码来自于 on-java-8

#静态方法

从 Java 8 开始可以在接口中定义静态方法,使用静态方法,可以恰当地把工具功能置于接口中,从而操作接口,或者使其成为通用的工具。使用静态方法就是将接口方法的 abstract 或者 default 换成 static。要使用接口名调用接口中的静态方法,不能使用接口的实现类的对象来调用接口的静态方法。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
interface InterfaceWithStatic {
    static void staticMethod() {
        System.out.println("This is a static method in interface.");
    }
}

public class InterfaceWithStaticImpl implements InterfaceWithStatic {
    public static void main(String[] args) {
        InterfaceWithStatic iws = new InterfaceWithStaticImpl();
        iws.staticMethod();  // 错误写法
        InterfaceWithStatic.staticMethod();  // 正确写法
    }
}

#私有方法

  • 解决问题:接口内多个默认方法之间存在重复代码的问题。静态私有方法解决多个静态方法中重复代码的问题。(从 Java 9 开始可以在接口中定义私有方法)

私有方法只能在接口内部使用,不能被接口的实现类或其它接口使用。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// 普通静态方法示例
interface InterfaceWithPrivate {
    default void firstMethod() {
        System.out.println("first method");
        privateMethod();
    }

    default void secondMethod() {
        System.out.println("second method");
        privateMethod();
    }

    private void privateMethod() {
        System.out.println("AAA");
        System.out.println("BBB");
        System.out.println("CCC");
    }
}

// 静态私有方法示例
interface InterfaceWithStaticPrivate {
    // 静态方法内部不能调用非静态的方法(除非给静态方法传递一个对象的引用,然后通过引用去访问非静态方法)
    // 所以需要 privateMethod 方法也是静态的
    static void firstMethod() {
        System.out.println("first method");
        privateMethod();
    }

    static void secondMethod() {
        System.out.println("second method");
        privateMethod();
    }

    private static void privateMethod() {
        System.out.println("AAA");
        System.out.println("BBB");
        System.out.println("CCC");
    }
}
updatedupdated2022-07-192022-07-19