其他分享
首页 > 其他分享> > 接口的默认方法定义和使用

接口的默认方法定义和使用

作者:互联网

默认方法的使用 可以继承,可以重写,二选一,但是只能通过实现类的对象来调用。 1. 继承默认方法,代码如下: 定义接口:
public interface LiveAble {
public default void fly(){
System.out.println("天上飞");
}
}
定义实现类:
public class Animal implements LiveAble {
// 继承,什么都不用写,直接调用
}
定义测试类:
public class InterfaceDemo {
public static void main(String[] args) {
// 创建子类对象
Animal a = new Animal();
// 调用默认方法
a.fly();
}
}
输出结果:
天上飞
2. 重写默认方法,代码如下: 定义接口:
public interface LiveAble {
public default void fly(){
System.out.println("天上飞");
}
}
定义实现类:
public class Animal implements LiveAble {
@Override
public void fly() {
System.out.println("自由自在的飞");
}
}
定义测试类:
public class InterfaceDemo {
public static void main(String[] args) {
// 创建子类对象
Animal a = new Animal();
// 调用重写方法
a.fly();
}
}
输出结果:
自由自在的飞

 

标签:fly,LiveAble,定义,void,接口,默认,Animal,public
来源: https://www.cnblogs.com/xuche/p/16441914.html