jdk8新特性

default关键字

定义一个Animal接口

其中breath用default修饰。

public interface Animal {

    void run();

    void eat();

    default void breath(){
        System.out.println("呼吸");
    }
}

定义一个Dog类

dog类实现Animal接口,我们发现Dog类在实现Animal接口时,并不需要实现breath()方法。

public class Dog implements Animal {

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

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

使用

public class MainDemo {

    @Test
    public void testDefault() {
        Dog dog = new Dog();
        dog.breath();
        dog.run();
        dog.eat();
    }
}

结果

image-20221003164339526

静态方法

定义一个接口

接口中定义一个静态方法

package chapter2;

public interface Animal {

    static void test() {
        System.out.println("Animal中的静态方法");
    }
}

使用

public class MainDemo {

    @Test
    public void testStatic() {
        Animal.test();
    }
}

结果

image-20221003164820675

posted @ 2022-10-03 18:24  jarico  阅读(25)  评论(0)    收藏  举报