抽象类和接口是Java面向对象编程的重要特性,它们提供了代码复用和多重继承的解决方案。本章将详细介绍抽象类和接口的概念、使用方法和最佳实践。

5.1 抽象类

5.1.1 抽象类基础

/**
 * 抽象类:车辆
 * 抽象类不能被实例化,只能被继承
 */
public abstract class Vehicle {
    // 实例变量
    protected String brand;        // 品牌
    protected String model;        // 型号
    protected int year;           // 年份
    protected double price;       // 价格
    protected boolean isRunning;  // 是否运行中
    
    // 静态变量
    protected static int totalVehicles = 0;
    
    // 构造方法
    public Vehicle(String brand, String model, int year, double price) {
        this.brand = brand;
        this.model = model;
        this.year = year;
        this.price = price;
        this.isRunning = false;
        totalVehicles++;
    }
    
    // 具体方法(子类可以直接使用)
    public void start() {
        if (!isRunning) {
            isRunning = true;
            System.out.println(brand + " " + model + " 启动了");
            onStart(); // 调用抽象方法
        } else {
            System.out.println("车辆已经在运行中");
        }
    }
    
    public void stop() {
        if (isRunning) {
            isRunning = false;
            System.out.println(brand + " " + model + " 停止了");
            onStop(); // 调用抽象方法
        } else {
            System.out.println("车辆已经停止");
        }
    }
    
    public void displayInfo() {
        System.out.println("=== 车辆信息 ===");
        System.out.println("品牌: " + brand);
        System.out.println("型号: " + model);
        System.out.println("年份: " + year);
        System.out.println("价格: $" + price);
        System.out.println("状态: " + (isRunning ? "运行中" : "停止"));
        System.out.println("类型: " + getVehicleType());
        System.out.println("最大速度: " + getMaxSpeed() + " km/h");
        System.out.println("燃料类型: " + getFuelType());
    }
    
    // 抽象方法(子类必须实现)
    public abstract String getVehicleType();
    public abstract double getMaxSpeed();
    public abstract String getFuelType();
    public abstract void accelerate(double speed);
    public abstract void brake();
    
    // 钩子方法(子类可以选择重写)
    protected void onStart() {
        System.out.println("车辆启动完成");
    }
    
    protected void onStop() {
        System.out.println("车辆停止完成");
    }
    
    // Getter和Setter方法
    public String getBrand() {
        return brand;
    }
    
    public String getModel() {
        return model;
    }
    
    public int getYear() {
        return year;
    }
    
    public double getPrice() {
        return price;
    }
    
    public boolean isRunning() {
        return isRunning;
    }
    
    public static int getTotalVehicles() {
        return totalVehicles;
    }
}

5.1.2 抽象类的具体实现

/**
 * 汽车类 - 继承抽象类Vehicle
 */
public class Car extends Vehicle {
    private int numberOfDoors;
    private String transmissionType; // 变速箱类型
    private double currentSpeed;
    
    public Car(String brand, String model, int year, double price, int numberOfDoors, String transmissionType) {
        super(brand, model, year, price);
        this.numberOfDoors = numberOfDoors;
        this.transmissionType = transmissionType;
        this.currentSpeed = 0.0;
    }
    
    // 实现抽象方法
    @Override
    public String getVehicleType() {
        return "汽车";
    }
    
    @Override
    public double getMaxSpeed() {
        return 200.0; // 假设最大速度200km/h
    }
    
    @Override
    public String getFuelType() {
        return "汽油";
    }
    
    @Override
    public void accelerate(double speed) {
        if (isRunning) {
            currentSpeed = Math.min(currentSpeed + speed, getMaxSpeed());
            System.out.println(brand + " " + model + " 加速到 " + currentSpeed + " km/h");
        } else {
            System.out.println("请先启动车辆");
        }
    }
    
    @Override
    public void brake() {
        if (currentSpeed > 0) {
            currentSpeed = Math.max(currentSpeed - 20, 0);
            System.out.println(brand + " " + model + " 刹车,当前速度: " + currentSpeed + " km/h");
        } else {
            System.out.println("车辆已经停止");
        }
    }
    
    // 重写钩子方法
    @Override
    protected void onStart() {
        System.out.println("汽车引擎启动," + transmissionType + "变速箱就绪");
    }
    
    @Override
    protected void onStop() {
        currentSpeed = 0;
        System.out.println("汽车引擎关闭,当前速度归零");
    }
    
    // 汽车特有方法
    public void honk() {
        System.out.println(brand + " " + model + " 鸣笛:嘀嘀!");
    }
    
    public void openTrunk() {
        System.out.println("打开后备箱");
    }
    
    // Getter方法
    public int getNumberOfDoors() {
        return numberOfDoors;
    }
    
    public String getTransmissionType() {
        return transmissionType;
    }
    
    public double getCurrentSpeed() {
        return currentSpeed;
    }
    
    @Override
    public void displayInfo() {
        super.displayInfo();
        System.out.println("车门数: " + numberOfDoors);
        System.out.println("变速箱: " + transmissionType);
        System.out.println("当前速度: " + currentSpeed + " km/h");
        System.out.println();
    }
}
/**
 * 摩托车类 - 继承抽象类Vehicle
 */
public class Motorcycle extends Vehicle {
    private boolean hasSidecar; // 是否有边车
    private double engineCapacity; // 发动机排量
    private double currentSpeed;
    
    public Motorcycle(String brand, String model, int year, double price, boolean hasSidecar, double engineCapacity) {
        super(brand, model, year, price);
        this.hasSidecar = hasSidecar;
        this.engineCapacity = engineCapacity;
        this.currentSpeed = 0.0;
    }
    
    // 实现抽象方法
    @Override
    public String getVehicleType() {
        return hasSidecar ? "边三轮摩托车" : "摩托车";
    }
    
    @Override
    public double getMaxSpeed() {
        return engineCapacity > 600 ? 180.0 : 120.0;
    }
    
    @Override
    public String getFuelType() {
        return "汽油";
    }
    
    @Override
    public void accelerate(double speed) {
        if (isRunning) {
            currentSpeed = Math.min(currentSpeed + speed, getMaxSpeed());
            System.out.println(brand + " " + model + " 加速到 " + currentSpeed + " km/h");
            if (currentSpeed > 80) {
                System.out.println("注意安全,摩托车高速行驶!");
            }
        } else {
            System.out.println("请先启动摩托车");
        }
    }
    
    @Override
    public void brake() {
        if (currentSpeed > 0) {
            currentSpeed = Math.max(currentSpeed - 15, 0);
            System.out.println(brand + " " + model + " 刹车,当前速度: " + currentSpeed + " km/h");
        } else {
            System.out.println("摩托车已经停止");
        }
    }
    
    @Override
    protected void onStart() {
        System.out.println("摩托车引擎启动," + engineCapacity + "cc发动机轰鸣");
    }
    
    @Override
    protected void onStop() {
        currentSpeed = 0;
        System.out.println("摩托车引擎关闭");
    }
    
    // 摩托车特有方法
    public void wheelie() {
        if (isRunning && currentSpeed > 30 && !hasSidecar) {
            System.out.println(brand + " " + model + " 做了一个后轮着地特技!");
        } else if (hasSidecar) {
            System.out.println("边三轮摩托车无法做后轮着地特技");
        } else {
            System.out.println("速度太慢,无法做特技");
        }
    }
    
    // Getter方法
    public boolean isHasSidecar() {
        return hasSidecar;
    }
    
    public double getEngineCapacity() {
        return engineCapacity;
    }
    
    public double getCurrentSpeed() {
        return currentSpeed;
    }
    
    @Override
    public void displayInfo() {
        super.displayInfo();
        System.out.println("边车: " + (hasSidecar ? "有" : "无"));
        System.out.println("发动机排量: " + engineCapacity + "cc");
        System.out.println("当前速度: " + currentSpeed + " km/h");
        System.out.println();
    }
}

5.2 接口

5.2.1 接口基础

/**
 * 可飞行接口
 */
public interface Flyable {
    // 常量(默认为public static final)
    double MAX_ALTITUDE = 10000.0; // 最大飞行高度
    String FLIGHT_MODE = "飞行模式";
    
    // 抽象方法(默认为public abstract)
    void takeOff();
    void land();
    void fly(double altitude);
    
    // 默认方法(Java 8+)
    default void checkWeather() {
        System.out.println("检查天气条件...");
        System.out.println("天气良好,适合飞行");
    }
    
    default void performPreFlightCheck() {
        System.out.println("执行飞行前检查...");
        checkWeather();
        System.out.println("飞行前检查完成");
    }
    
    // 静态方法(Java 8+)
    static double convertAltitude(double meters) {
        return meters * 3.28084; // 米转英尺
    }
    
    static void printFlightRegulations() {
        System.out.println("=== 飞行规定 ===");
        System.out.println("1. 最大飞行高度: " + MAX_ALTITUDE + "米");
        System.out.println("2. 必须进行飞行前检查");
        System.out.println("3. 遵守空中交通管制");
    }
}
/**
 * 可游泳接口
 */
public interface Swimmable {
    // 常量
    double MAX_DEPTH = 100.0; // 最大游泳深度
    
    // 抽象方法
    void swim();
    void dive(double depth);
    void surface();
    
    // 默认方法
    default void checkWaterConditions() {
        System.out.println("检查水质和温度...");
        System.out.println("水质良好,适合游泳");
    }
    
    default double getMaxSafeDepth() {
        return MAX_DEPTH * 0.8; // 安全深度为最大深度的80%
    }
}
/**
 * 可充电接口
 */
public interface Rechargeable {
    // 常量
    int MAX_BATTERY_LEVEL = 100;
    int MIN_BATTERY_LEVEL = 0;
    
    // 抽象方法
    void charge();
    void discharge();
    int getBatteryLevel();
    
    // 默认方法
    default boolean needsCharging() {
        return getBatteryLevel() < 20;
    }
    
    default void checkBatteryStatus() {
        int level = getBatteryLevel();
        System.out.println("电池电量: " + level + "%");
        
        if (level < 10) {
            System.out.println("警告:电池电量极低!");
        } else if (level < 20) {
            System.out.println("提示:电池电量较低,建议充电");
        } else if (level > 90) {
            System.out.println("电池电量充足");
        }
    }
}

5.2.2 接口的实现

/**
 * 无人机类 - 实现多个接口
 */
public class Drone implements Flyable, Rechargeable {
    private String model;
    private double currentAltitude;
    private boolean isFlying;
    private int batteryLevel;
    private double maxFlightTime; // 最大飞行时间(分钟)
    
    public Drone(String model, double maxFlightTime) {
        this.model = model;
        this.maxFlightTime = maxFlightTime;
        this.currentAltitude = 0.0;
        this.isFlying = false;
        this.batteryLevel = 100;
    }
    
    // 实现Flyable接口
    @Override
    public void takeOff() {
        if (!isFlying && batteryLevel > 10) {
            performPreFlightCheck();
            isFlying = true;
            currentAltitude = 10.0; // 起飞到10米高度
            System.out.println(model + " 无人机起飞,当前高度: " + currentAltitude + "米");
            discharge(); // 起飞消耗电量
        } else if (batteryLevel <= 10) {
            System.out.println("电量不足,无法起飞");
        } else {
            System.out.println("无人机已在飞行中");
        }
    }
    
    @Override
    public void land() {
        if (isFlying) {
            System.out.println(model + " 无人机降落");
            currentAltitude = 0.0;
            isFlying = false;
        } else {
            System.out.println("无人机已在地面");
        }
    }
    
    @Override
    public void fly(double altitude) {
        if (!isFlying) {
            System.out.println("请先起飞");
            return;
        }
        
        if (altitude > MAX_ALTITUDE) {
            System.out.println("超过最大飞行高度限制: " + MAX_ALTITUDE + "米");
            return;
        }
        
        if (batteryLevel < 5) {
            System.out.println("电量不足,开始自动降落");
            land();
            return;
        }
        
        currentAltitude = altitude;
        System.out.println(model + " 飞行到 " + altitude + "米高度");
        discharge(); // 飞行消耗电量
    }
    
    // 重写默认方法
    @Override
    public void checkWeather() {
        System.out.println("无人机气象传感器检测中...");
        System.out.println("风速: 5 m/s, 能见度: 良好");
    }
    
    // 实现Rechargeable接口
    @Override
    public void charge() {
        if (isFlying) {
            System.out.println("无法在飞行中充电,请先降落");
            return;
        }
        
        System.out.println("开始为 " + model + " 充电...");
        while (batteryLevel < MAX_BATTERY_LEVEL) {
            batteryLevel = Math.min(batteryLevel + 10, MAX_BATTERY_LEVEL);
            System.out.println("充电中... 当前电量: " + batteryLevel + "%");
            
            // 模拟充电时间
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        System.out.println("充电完成!");
    }
    
    @Override
    public void discharge() {
        if (batteryLevel > MIN_BATTERY_LEVEL) {
            batteryLevel = Math.max(batteryLevel - 5, MIN_BATTERY_LEVEL);
            checkBatteryStatus();
        }
    }
    
    @Override
    public int getBatteryLevel() {
        return batteryLevel;
    }
    
    // 无人机特有方法
    public void takePhoto() {
        if (isFlying) {
            System.out.println(model + " 在 " + currentAltitude + "米高度拍摄照片");
            discharge();
        } else {
            System.out.println("请先起飞后再拍摄");
        }
    }
    
    public void recordVideo(int duration) {
        if (isFlying) {
            System.out.println(model + " 开始录制 " + duration + " 秒视频");
            for (int i = 0; i < duration / 5; i++) {
                discharge();
                if (batteryLevel <= 0) {
                    System.out.println("电量耗尽,停止录制");
                    land();
                    break;
                }
            }
            System.out.println("视频录制完成");
        } else {
            System.out.println("请先起飞后再录制");
        }
    }
    
    public void displayStatus() {
        System.out.println("=== " + model + " 状态 ===");
        System.out.println("飞行状态: " + (isFlying ? "飞行中" : "地面"));
        System.out.println("当前高度: " + currentAltitude + "米");
        System.out.println("电池电量: " + batteryLevel + "%");
        System.out.println("最大飞行时间: " + maxFlightTime + "分钟");
        System.out.println();
    }
}
/**
 * 水陆两栖车 - 继承Vehicle并实现Swimmable接口
 */
public class AmphibiousVehicle extends Vehicle implements Swimmable {
    private boolean isInWater;
    private double currentDepth;
    private double maxDepth;
    
    public AmphibiousVehicle(String brand, String model, int year, double price, double maxDepth) {
        super(brand, model, year, price);
        this.maxDepth = Math.min(maxDepth, MAX_DEPTH);
        this.isInWater = false;
        this.currentDepth = 0.0;
    }
    
    // 实现Vehicle抽象方法
    @Override
    public String getVehicleType() {
        return "水陆两栖车";
    }
    
    @Override
    public double getMaxSpeed() {
        return isInWater ? 20.0 : 80.0; // 水中速度较慢
    }
    
    @Override
    public String getFuelType() {
        return "柴油";
    }
    
    @Override
    public void accelerate(double speed) {
        if (isRunning) {
            String mode = isInWater ? "游泳" : "陆地行驶";
            System.out.println(brand + " " + model + " 在" + mode + "模式下加速");
        } else {
            System.out.println("请先启动车辆");
        }
    }
    
    @Override
    public void brake() {
        if (isInWater) {
            System.out.println("在水中减速停止");
        } else {
            System.out.println("在陆地上刹车停止");
        }
    }
    
    // 实现Swimmable接口
    @Override
    public void swim() {
        if (!isInWater) {
            System.out.println("请先进入水中");
            return;
        }
        
        if (isRunning) {
            System.out.println(brand + " " + model + " 在水面游泳");
        } else {
            System.out.println("请先启动引擎");
        }
    }
    
    @Override
    public void dive(double depth) {
        if (!isInWater) {
            System.out.println("请先进入水中");
            return;
        }
        
        if (depth > maxDepth) {
            System.out.println("超过最大潜水深度: " + maxDepth + "米");
            return;
        }
        
        currentDepth = depth;
        System.out.println(brand + " " + model + " 潜水到 " + depth + "米深度");
    }
    
    @Override
    public void surface() {
        if (currentDepth > 0) {
            System.out.println(brand + " " + model + " 从 " + currentDepth + "米深度浮出水面");
            currentDepth = 0.0;
        } else {
            System.out.println("已在水面");
        }
    }
    
    // 两栖车特有方法
    public void enterWater() {
        if (!isInWater) {
            isInWater = true;
            System.out.println(brand + " " + model + " 进入水中,切换到水上模式");
            checkWaterConditions();
        } else {
            System.out.println("已在水中");
        }
    }
    
    public void exitWater() {
        if (isInWater) {
            surface(); // 先浮出水面
            isInWater = false;
            System.out.println(brand + " " + model + " 离开水面,切换到陆地模式");
        } else {
            System.out.println("已在陆地");
        }
    }
    
    @Override
    public void displayInfo() {
        super.displayInfo();
        System.out.println("当前环境: " + (isInWater ? "水中" : "陆地"));
        System.out.println("当前深度: " + currentDepth + "米");
        System.out.println("最大潜水深度: " + maxDepth + "米");
        System.out.println();
    }
}

5.2.3 接口的高级特性

/**
 * 多接口继承示例
 */
public interface AdvancedFlyable extends Flyable {
    // 扩展飞行功能
    void hover(); // 悬停
    void performAerobatics(); // 特技飞行
    
    // 重写父接口的默认方法
    @Override
    default void performPreFlightCheck() {
        System.out.println("执行高级飞行前检查...");
        checkWeather();
        checkAdvancedSystems();
        System.out.println("高级飞行前检查完成");
    }
    
    default void checkAdvancedSystems() {
        System.out.println("检查高级飞行系统...");
        System.out.println("GPS导航系统: 正常");
        System.out.println("自动驾驶系统: 正常");
        System.out.println("碰撞避免系统: 正常");
    }
}
/**
 * 智能接口 - 演示接口中的静态方法和默认方法
 */
public interface SmartDevice {
    // 常量
    String MANUFACTURER = "SmartTech";
    String VERSION = "2.0";
    
    // 抽象方法
    void turnOn();
    void turnOff();
    String getDeviceId();
    
    // 默认方法
    default void connectToWiFi(String networkName, String password) {
        System.out.println("连接到WiFi网络: " + networkName);
        System.out.println("连接成功!");
    }
    
    default void updateFirmware() {
        System.out.println("检查固件更新...");
        System.out.println("当前版本: " + VERSION);
        System.out.println("固件已是最新版本");
    }
    
    default void performDiagnostics() {
        System.out.println("=== 设备诊断 ===");
        System.out.println("设备ID: " + getDeviceId());
        System.out.println("制造商: " + MANUFACTURER);
        System.out.println("版本: " + VERSION);
        System.out.println("诊断完成");
    }
    
    // 静态方法
    static void printManufacturerInfo() {
        System.out.println("制造商: " + MANUFACTURER);
        System.out.println("当前版本: " + VERSION);
    }
    
    static boolean isCompatible(String version) {
        return version.compareTo("1.0") >= 0;
    }
}

5.3 抽象类与接口的综合应用

5.3.1 综合示例

/**
 * 高级无人机 - 继承抽象类并实现多个接口
 */
public class AdvancedDrone extends Vehicle implements AdvancedFlyable, Rechargeable, SmartDevice {
    private double currentAltitude;
    private boolean isFlying;
    private int batteryLevel;
    private String deviceId;
    private boolean isHovering;
    private boolean systemsOnline;
    
    public AdvancedDrone(String brand, String model, int year, double price, String deviceId) {
        super(brand, model, year, price);
        this.deviceId = deviceId;
        this.currentAltitude = 0.0;
        this.isFlying = false;
        this.batteryLevel = 100;
        this.isHovering = false;
        this.systemsOnline = false;
    }
    
    // 实现Vehicle抽象方法
    @Override
    public String getVehicleType() {
        return "高级无人机";
    }
    
    @Override
    public double getMaxSpeed() {
        return 150.0;
    }
    
    @Override
    public String getFuelType() {
        return "电池";
    }
    
    @Override
    public void accelerate(double speed) {
        if (isFlying && !isHovering) {
            System.out.println(brand + " " + model + " 加速飞行");
            discharge();
        } else if (isHovering) {
            System.out.println("退出悬停模式后再加速");
        } else {
            System.out.println("请先起飞");
        }
    }
    
    @Override
    public void brake() {
        if (isFlying) {
            System.out.println("减速并进入悬停模式");
            hover();
        }
    }
    
    // 实现AdvancedFlyable接口
    @Override
    public void takeOff() {
        if (!systemsOnline) {
            System.out.println("请先开启设备");
            return;
        }
        
        if (!isFlying && batteryLevel > 15) {
            performPreFlightCheck();
            isFlying = true;
            currentAltitude = 10.0;
            System.out.println(brand + " " + model + " 高级无人机起飞成功");
            discharge();
        } else if (batteryLevel <= 15) {
            System.out.println("电量不足,无法起飞");
        } else {
            System.out.println("无人机已在飞行中");
        }
    }
    
    @Override
    public void land() {
        if (isFlying) {
            System.out.println("启动自动降落程序...");
            isHovering = false;
            currentAltitude = 0.0;
            isFlying = false;
            System.out.println("降落完成");
        } else {
            System.out.println("无人机已在地面");
        }
    }
    
    @Override
    public void fly(double altitude) {
        if (!isFlying) {
            System.out.println("请先起飞");
            return;
        }
        
        if (altitude > MAX_ALTITUDE) {
            System.out.println("超过最大飞行高度限制");
            return;
        }
        
        isHovering = false;
        currentAltitude = altitude;
        System.out.println("飞行到 " + altitude + "米高度");
        discharge();
    }
    
    @Override
    public void hover() {
        if (isFlying) {
            isHovering = true;
            System.out.println("进入悬停模式,高度: " + currentAltitude + "米");
        } else {
            System.out.println("请先起飞");
        }
    }
    
    @Override
    public void performAerobatics() {
        if (isFlying && batteryLevel > 30 && currentAltitude > 50) {
            System.out.println("执行特技飞行动作...");
            System.out.println("完成360度翻滚!");
            discharge();
            discharge(); // 特技飞行消耗更多电量
        } else if (batteryLevel <= 30) {
            System.out.println("电量不足,无法执行特技飞行");
        } else if (currentAltitude <= 50) {
            System.out.println("高度不够,无法安全执行特技飞行");
        } else {
            System.out.println("请先起飞");
        }
    }
    
    // 实现Rechargeable接口
    @Override
    public void charge() {
        if (isFlying) {
            System.out.println("无法在飞行中充电,请先降落");
            return;
        }
        
        System.out.println("开始快速充电...");
        batteryLevel = MAX_BATTERY_LEVEL;
        System.out.println("充电完成!电量: " + batteryLevel + "%");
    }
    
    @Override
    public void discharge() {
        if (batteryLevel > MIN_BATTERY_LEVEL) {
            batteryLevel = Math.max(batteryLevel - 3, MIN_BATTERY_LEVEL);
            if (batteryLevel <= 10 && isFlying) {
                System.out.println("电量严重不足,启动紧急降落程序");
                land();
            }
        }
    }
    
    @Override
    public int getBatteryLevel() {
        return batteryLevel;
    }
    
    // 实现SmartDevice接口
    @Override
    public void turnOn() {
        if (!systemsOnline) {
            systemsOnline = true;
            System.out.println("高级无人机系统启动中...");
            performDiagnostics();
            System.out.println("所有系统就绪");
        } else {
            System.out.println("设备已开启");
        }
    }
    
    @Override
    public void turnOff() {
        if (isFlying) {
            System.out.println("无法在飞行中关闭,请先降落");
            return;
        }
        
        if (systemsOnline) {
            systemsOnline = false;
            System.out.println("关闭高级无人机系统");
        } else {
            System.out.println("设备已关闭");
        }
    }
    
    @Override
    public String getDeviceId() {
        return deviceId;
    }
    
    // 高级无人机特有方法
    public void autoReturn() {
        if (isFlying) {
            System.out.println("启动自动返航程序...");
            System.out.println("GPS导航至起飞点");
            land();
        } else {
            System.out.println("无人机未在飞行中");
        }
    }
    
    public void emergencyLanding() {
        if (isFlying) {
            System.out.println("执行紧急降落程序!");
            isHovering = false;
            land();
        }
    }
    
    @Override
    public void displayInfo() {
        super.displayInfo();
        System.out.println("设备ID: " + deviceId);
        System.out.println("系统状态: " + (systemsOnline ? "在线" : "离线"));
        System.out.println("飞行状态: " + (isFlying ? "飞行中" : "地面"));
        System.out.println("当前高度: " + currentAltitude + "米");
        System.out.println("悬停状态: " + (isHovering ? "悬停中" : "正常飞行"));
        System.out.println("电池电量: " + batteryLevel + "%");
        System.out.println();
    }
}

5.3.2 综合演示程序

public class AbstractAndInterfaceDemo {
    public static void main(String[] args) {
        System.out.println("=== 抽象类和接口综合演示 ===");
        
        // 创建不同类型的对象
        Car car = new Car("丰田", "凯美瑞", 2023, 25000, 4, "自动");
        Motorcycle motorcycle = new Motorcycle("哈雷", "Street 750", 2023, 8000, false, 750);
        Drone drone = new Drone("DJI", "Mavic Pro", 30);
        AmphibiousVehicle amphibious = new AmphibiousVehicle("DUKW", "Duck", 2023, 50000, 5.0);
        AdvancedDrone advancedDrone = new AdvancedDrone("军用", "Predator", 2023, 100000, "ADV-001");
        
        System.out.println("=== 车辆演示 ===");
        // 车辆基本操作
        car.displayInfo();
        car.start();
        car.accelerate(50);
        car.honk();
        car.brake();
        car.stop();
        
        System.out.println("\n=== 摩托车演示 ===");
        motorcycle.displayInfo();
        motorcycle.start();
        motorcycle.accelerate(60);
        motorcycle.wheelie();
        motorcycle.brake();
        motorcycle.stop();
        
        System.out.println("\n=== 无人机演示 ===");
        drone.displayStatus();
        drone.takeOff();
        drone.fly(100);
        drone.takePhoto();
        drone.recordVideo(10);
        drone.land();
        
        // 检查电量并充电
        if (drone.needsCharging()) {
            drone.charge();
        }
        
        System.out.println("\n=== 水陆两栖车演示 ===");
        amphibious.displayInfo();
        amphibious.start();
        amphibious.accelerate(30);
        
        // 进入水中
        amphibious.enterWater();
        amphibious.swim();
        amphibious.dive(3.0);
        amphibious.surface();
        amphibious.exitWater();
        amphibious.stop();
        
        System.out.println("\n=== 高级无人机演示 ===");
        advancedDrone.displayInfo();
        
        // 智能设备操作
        SmartDevice.printManufacturerInfo();
        advancedDrone.turnOn();
        advancedDrone.connectToWiFi("DroneNet", "password123");
        advancedDrone.updateFirmware();
        
        // 飞行操作
        advancedDrone.takeOff();
        advancedDrone.fly(200);
        advancedDrone.hover();
        advancedDrone.performAerobatics();
        advancedDrone.autoReturn();
        
        advancedDrone.turnOff();
        
        System.out.println("\n=== 多态演示 ===");
        // 多态:使用接口引用
        Flyable[] flyableObjects = {drone, advancedDrone};
        
        for (Flyable flyable : flyableObjects) {
            System.out.println("\n飞行对象操作:");
            Flyable.printFlightRegulations();
            flyable.performPreFlightCheck();
            flyable.takeOff();
            flyable.fly(50);
            flyable.land();
        }
        
        // 可充电设备
        Rechargeable[] rechargeableDevices = {drone, advancedDrone};
        
        System.out.println("\n=== 充电设备管理 ===");
        for (Rechargeable device : rechargeableDevices) {
            device.checkBatteryStatus();
            if (device.needsCharging()) {
                device.charge();
            }
        }
        
        // 统计信息
        System.out.println("\n=== 统计信息 ===");
        System.out.println("总车辆数量: " + Vehicle.getTotalVehicles());
        
        // 接口静态方法调用
        System.out.println("\n高度转换示例:");
        double meters = 1000;
        double feet = Flyable.convertAltitude(meters);
        System.out.println(meters + "米 = " + String.format("%.2f", feet) + "英尺");
    }
}

本章小结

本章详细介绍了Java中的抽象类和接口:

抽象类特点:

  • 使用abstract关键字声明
  • 不能被实例化,只能被继承
  • 可以包含抽象方法和具体方法
  • 可以有构造方法、实例变量和静态变量
  • 子类必须实现所有抽象方法

接口特点:

  • 使用interface关键字声明
  • 默认方法为public abstract
  • 变量默认为public static final
  • 支持默认方法和静态方法(Java 8+)
  • 类可以实现多个接口
  • 接口可以继承其他接口

选择原则:

  • 当需要为相关类提供公共代码时,使用抽象类
  • 当需要指定特定行为契约时,使用接口
  • 当需要多重继承时,使用接口
  • 抽象类适合”is-a”关系,接口适合”can-do”关系

下一章预告

下一章我们将学习Java中的异常处理机制,包括异常的分类、try-catch语句、自定义异常等内容。

练习题

  1. 设计一个图形绘制系统,包含抽象类Drawable和接口ColorableResizable
  2. 创建一个媒体播放器系统,支持不同格式的音频和视频文件
  3. 实现一个智能家居控制系统,包含各种智能设备的抽象和接口定义
  4. 设计一个游戏角色系统,包含不同类型的角色和技能接口
  5. 创建一个交通工具管理系统,演示抽象类继承和接口实现的综合应用