Java8在接口中的default方法

java8为啥引入接口中的default方法

因为在java8之前,只要类实现了接口,那么就必须实现接口的全部方法,否则就无法编译通过。

接口中default方法用法

未覆盖的default方法

public interface IPerson {

    void run();

    default void sleep() {
        System.out.println("=========== sleep方法");
    }
}

public class YellowPerson implements IPerson{

    @Override
    public void run() {
        System.out.println("=========== run方法");
    }

    public static void main(String[] args) {
        YellowPerson yellowPerson = new YellowPerson();
        yellowPerson.run();
    }
}

结果:

image

覆盖的default方法

public interface IPerson {

    void run();

    default void sleep() {
        System.out.println("=========== IPerson.sleep方法");
    }
}

public class YellowPerson implements IPerson{

    @Override
    public void run() {
        System.out.println("=========== run方法");
    }

    @Override
    public void sleep() {
        System.out.println("=========== YellowPerson.sleep方法");
    }

    public static void main(String[] args) {
        YellowPerson yellowPerson = new YellowPerson();
        yellowPerson.run();
        yellowPerson.sleep();
    }
}

结果:

image

类实现的两个接口出现一样的default方法

那么实现类必须覆盖接口的方法,要不然就会编译不通过

public interface IColor {

    default void doBus() {
        System.out.println("=========== IColor.doBus方法");
    }
}

public interface IPerson {

    void run();

    default void doBus() {
        System.out.println("=========== IPerson.doBus方法");
    }
}

public class YellowPerson implements IPerson, IColor {

    @Override
    public void run() {
        System.out.println("=========== run方法");
    }

    @Override
    public void doBus() {
        System.out.println("============= YellowPerson.doBus");
    }

    public static void main(String[] args) {
        YellowPerson yellowPerson = new YellowPerson();
        yellowPerson.run();
        yellowPerson.doBus();
    }
}

结果:

image

posted @ 2023-06-04 20:11  sunpeiyu  阅读(179)  评论(0编辑  收藏  举报