public class Vehicles {
    String brand;
    String color;

    public Vehicles(String brand, String color) {
        this.brand = brand;
        this.color = color;
    }

    public void run() {
        System.out.println('我已经开动了');
    }

    public void showInfo() {
        System.out.println('商标:' + brand + ',颜色:' + color);
    }
}

public class Car extends Vehicles {
    int seats;

    public Car(String brand, String color, int seats) {
        super(brand, color);
        this.seats = seats;
    }

    public void showCar() {
        System.out.println('这是一辆' + color + '的' + brand + '小汽车,有' + seats + '个座位');
    }
}

public class Truck extends Vehicles {
    float load;

    public Truck(String brand, String color, float load) {
        super(brand, color);
        this.load = load;
    }

    public void showTruck() {
        System.out.println('这是一辆' + color + '的' + brand + '卡车,载重' + load + '吨');
    }
}

public class Main {
    public static void main(String[] args) {
        Car car = new Car('宝马', '黑色', 5);
        car.showInfo();
        car.showCar();

        Truck truck = new Truck('东风', '红色', 10.5f);
        truck.showInfo();
        truck.showTruck();
    }
}

输出结果为:

商标:宝马,颜色:黑色
这是一辆黑色的宝马小汽车,有5个座位
商标:东风,颜色:红色
这是一辆红色的东风卡车,载重10.5吨
Java面向对象编程:交通工具类、小汽车类和卡车类的设计与实现

原文地址: https://www.cveoy.top/t/topic/odXQ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录