Interface Abstract Class

发布时间:2026/5/15 13:22:08

Interface  Abstract Class Interface Abstract Class 接口与抽象类package further.zwf.interface2; /** * 1. 接口定义“能飞”的规范JDK 8 带默认方法 * * author ZengWenFeng * date 2023.09.17 * mobile 13805029595 * email 117791303QQ.COM */ interface Flyable { //llegal modifier for the interface field Flyable.id; only public, static final are permitted //private String id; public static final int a 100; // 抽象方法必须由实现类实现 void fly(); // JDK 8 新增默认方法有实现实现类可直接用或重写 default void takeOff() { System.out.println(准备起飞...); } // JDK 8 新增静态方法属于接口本身 static void showInfo() { System.out.println(这是一个定义飞行行为的接口); } }package further.zwf.interface2; /** * 2. 抽象类定义“交通工具”的通用模板 * * author ZengWenFeng * date 2023.09.17 * mobile 13805029595 * email 117791303QQ.COM */ public abstract class Vehicle { // 普通成员变量抽象类可以有状态 protected String name; // private String id; public String code; String sex; // 构造方法供子类调用 public Vehicle(String name) { this.name name; } // 抽象方法子类必须实现 public abstract void run(); // 普通方法通用逻辑子类直接复用 public void start() { System.out.println(name 启动了); } public void stop() { System.out.println(name 停下了); } }package further.zwf.interface2; /** * 3. 飞机类继承抽象类 实现接口多继承 * * author ZengWenFeng * date 2023.09.17 * mobile 13805029595 * email 117791303QQ.COM */ public class Airplane extends Vehicle implements Flyable { public Airplane(String name) { super(name); } // 实现抽象类的抽象方法 public void run() { System.out.println(name 在跑道上滑行); } // 实现接口的抽象方法 public void fly() { System.out.println(name 在高空飞行); } // 可以重写接口的默认方法也可以不写直接用 public void takeOff() { System.out.println(name 加速、拉升起飞); } }package further.zwf.interface2; /** * 4. 鸟类实现接口不继承抽象类和交通工具没关系但也能飞 * * author ZengWenFeng * date 2023.09.17 * mobile 13805029595 * email 117791303QQ.COM */ public class Bird implements Flyable { private String name; public Bird(String name) { this.name name; } public void fly() { System.out.println(name 扇着翅膀在天空飞); } }package further.zwf.interface2; /** * 5.测试类 * 其实我是个笨蛋特别是看书 * 书有时候太抽象概念太多不太容易理解 * 所以多动手写例子 * * author ZengWenFeng * date 2023.09.17 * mobile 13805029595 * email 117791303QQ.COM */ public class TestDemo { public static void main(String[] args) { // 调用接口的静态方法 Flyable.showInfo(); // 飞机既继承了交通工具的通用方法又实现了飞行接口 Airplane plane new Airplane(波音747); plane.start(); // 来自抽象类的通用方法 plane.takeOff(); // 重写后的接口默认方法 plane.fly(); // 接口的抽象方法实现 plane.run(); // 抽象类的抽象方法实现 plane.stop(); // 来自抽象类的通用方法 System.out.println(----------------); // 鸟只实现飞行接口和交通工具无关 Bird bird new Bird(麻雀); bird.takeOff(); // 直接使用接口的默认方法 bird.fly(); } }

相关新闻