Java基础系列--接口

jdk1.8的接口新特性

default

其他网址

jdk1.8新特性之default关键字 - lcnb - 博客园

JDK1.8增加default方法。实际开发中应该谨慎使用:在复杂的继承体系中,默认方法可能引起歧义和编译错误。

package com.example;

interface MyInterface{
    default void sayHello(){
        System.out.println("sayHello");
    }
}

class MyInterfaceImpl implements MyInterface{

    public void test(){
        MyInterface myInterface = new MyInterfaceImpl();
        myInterface.sayHello();
    }
}

public class Demo {
    public static void main(String[] args) {
        MyInterfaceImpl impl = new MyInterfaceImpl();
        impl.test();
    }
}

运行结果

sayHello

 注意:如果两个接口都用default修饰同一方法,则会报错

package com.example;

interface MyInterface1{
    default void sayHello(){
        System.out.println("sayHello(1)");
    }
}

interface MyInterface2{
    default void sayHello(){
        System.out.println("sayHello(2)");
    }
}

class MyInterfaceImpl implements MyInterface1,MyInterface2{
    public void test(){
        MyInterface1 myInterface = new MyInterfaceImpl();
        myInterface.sayHello();
    }
}

public class Demo {
    public static void main(String[] args) {
        MyInterfaceImpl impl = new MyInterfaceImpl();
        impl.test();
    }
}

解决办法:在实现类中重写该方法。

package com.example;

interface MyInterface1{
    default void sayHello(){
        System.out.println("sayHello(1)");
    }
}

interface MyInterface2{
    default void sayHello(){
        System.out.println("sayHello(2)");
    }
}

class MyInterfaceImpl implements MyInterface1,MyInterface2{
    public void test(){
        MyInterface1 myInterface = new MyInterfaceImpl();
        myInterface.sayHello();
    }

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

public class Demo {
    public static void main(String[] args) {
        MyInterfaceImpl impl = new MyInterfaceImpl();
        impl.test();
    }
}

运行结果

sayHello(Impl)

static

JDK1.8新增了static函数。static修饰的方法也是非抽象方法,有自己的方法体,在接口中定义一个静态方法,该方法可以直接用< 接口名.方法名() >的形式来调用。相当于调用类的静态方法一样

package com.example;

interface MyInterface{
    static void sayHello(){
        System.out.println("sayHello");
    }
}

public class Demo {
    public static void main(String[] args) {
        MyInterface.sayHello();
    }
}

运行结果

sayHello

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章