Java默认方法

示例1

interface InterfaceA {
    default void say() {
        System.out.println("InterfaceA");
    }
}
public class DefaultMethod implements InterfaceA{
    public static void main(String[] args) {
        new DefaultMethod().say();
    }

}

输出

InterfaceA

 示例2 实现类重写default方法

interface InterfaceA {
    default void say() {
        System.out.println("InterfaceA");
    }
}
public class DefaultMethod implements InterfaceA{
    public void say() {
        System.out.println("DefaultMethod");
    }
    public static void main(String[] args) {
        new DefaultMethod().say();
    }

}

输出

DefaultMethod

 示例3

interface InterfaceA {
    default void say(double m) {
        System.out.println("InterfaceA");
    }
}
public class DefaultMethod implements InterfaceA{
    public void say(int m) {
        System.out.println("DefaultMethod");
    }
    public static void main(String[] args) {
        DefaultMethod defaultMethod = new DefaultMethod();
        defaultMethod.say(1);
        defaultMethod.say(1L);
    }

}

输出

DefaultMethod
InterfaceA

 示例4

interface InterfaceA {
    default void say() {
        System.out.println("InterfaceA");
    }
}
interface InterfaceAA extends InterfaceA{
    void say();
}
public class DefaultMethod implements InterfaceAA{
    public static void main(String[] args) {
        DefaultMethod defaultMethod = new DefaultMethod();
        defaultMethod.say();
    }
}

 输出 报错

示例5

interface InterfaceA {
    default void say() {
        System.out.println("InterfaceA");
    }
}
interface InterfaceAA extends InterfaceA{
    void say();
}
public class DefaultMethod implements InterfaceAA{
    public static void main(String[] args) {
        DefaultMethod defaultMethod = new DefaultMethod();
        defaultMethod.say();
    }

    @Override
    public void say() {
        System.out.println("defaultMethod");
        
    }
}

输出

defaultMethod

 示例6

interface InterfaceA {
    default void say() {
        System.out.println("InterfaceA");
    }
}
interface InterfaceB {
    default void say() {
        System.out.println("InterfaceB");
    }
}
public class DefaultMethod implements InterfaceA,InterfaceB{
    public static void main(String[] args) {
        DefaultMethod defaultMethod = new DefaultMethod();
        defaultMethod.say();
    }
}

输出 报错

示例7

interface InterfaceA {
    default void say() {
        System.out.println("InterfaceA");
    }
}
interface InterfaceB {
    default void say() {
        System.out.println("InterfaceB");
    }
}
public class DefaultMethod implements InterfaceA,InterfaceB{
    public static void main(String[] args) {
        DefaultMethod defaultMethod = new DefaultMethod();
        defaultMethod.say();
    }
    @Override
    public void say() {
        InterfaceA.super.say();
        InterfaceB.super.say();
    }
}

输出

InterfaceA
InterfaceB

猜你喜欢

转载自www.cnblogs.com/j-j-c-c/p/8948114.html