java8新特性:interface中的static方法和default方法

java8中接口有两个新特性,一个是静态方法,一个是默认方法。

static方法

java8中为接口新增了一项功能:定义一个或者多个静态方法。

定义用法和普通的static方法一样:

public interface InterfaceTest {
    /**
     * 接口中的静态方法
     */
    static void testStatic() {
        System.out.println("我是接口的一个静态方法");
    }
}

调用的方式和静态类调用静态方法一样:

InterfaceTest.testStatic(); // 我是接口的一个静态方法

这里要注意的是,实现接口的类或者子接口不会继承接口中的静态方法。

default方法

在接口中,增加default方法,是为了既有的成千上万的Java类库的类增加新的功能,且不必对这些类进行重新设计。因此它既被称为默认方法,又被称为拓展方法。

比如说,只需要在Collection接口中增加default Stream stream(),相应的Set和List接口以及它们的子类都会包含此方法,不必再去为每个子类重新copy这个方法。

default方法的出现,允许了我们在接口中添加非抽象的方法实现。

实现单一接口,仅实现接口:

public interface InterfaceTest {
    /**
     * 接口下的静态方法
     */
    static void testStatic() {
        System.out.println("我是接口下的静态方法");
    }

    /**
     * 接口下的默认方法
     */
    default void testDefault() {
        System.out.println("我是接口下的默认方法");
    }

}

/**
 * 只实现这个接口
 */
public class InterfaceTestImpl implements InterfaceTest {

}

仅实现接口的运行:

InterfaceTest.testStatic(); // 我是接口下的静态方法
new InterfaceTestImpl().testDefault(); // 我是接口下的默认方法

如果接口中的默认方法不能满足某个实现类的需要,那么实现类可以覆盖默认方法。

实现单一接口,并重写接口中的default方法:

public class InterfaceTestImpl implements InterfaceTest {
    /**
     * 跟接口default方法一致,但不能再加default修饰符
     */
    @Override
    public void testDefault(){
        System.out.println("我重写了接口的默认方法");
    }
}

重写了default方法的运行:

InterfaceTest.testStatic(); // 我是接口下的静态方法
new InterfaceTestImpl().testDefault(); // 我重写了接口的默认方法

实现多个接口,且接口中拥有相同的default方法和static方法:

public class InterfaceATestImpl implements InterfaceTest, InterfaceTest1{
    @Override
    public void testDefault() {
        System.out.println("我重写了两个接口相同的默认方法");
    }
}

重写了两个接口相同的default方法的运行:

InterfaceTest.testStatic(); // 我是接口下的静态方法
new InterfaceTestImpl().testDefault(); // 我重写了两个接口相同的默认方法

如果实现多个接口的时候,每个接口都有相同的default方法,则必须要重写该方法。

人的前半生没有对错,只有成长。

猜你喜欢

转载自www.cnblogs.com/yanggb/p/10593052.html