定义一个名为Vehicles(交通工具)的基类,并添加brand(品牌)和color(颜色),以及成员方法run(行驶,在控制台显示“我已经开动了”),showInfo(显示品牌和颜色),添加构造方法对成员属性初始化。编写Car类继承于Vehicles类,增加int型成员属性seats(座位)和成员方法showCar(在控制台显示小汽车的信息),并编写构造方法对其初始化。编写Truck(卡车)类继承于Vehicles类,增加float型成员属性load(载重)和成员方法showTruck(在控制台显示卡车的信息),并编写构造方法。在main方法中new对象v1,c1,t1,并调用方法在控制台显示成员信息。
代码:
public class Vehicles {
private String brand;
private 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);
System.out.println("颜色: " + color);
}
}
public class Car extends Vehicles {
private int seats;
public Car(String brand, String color, int seats) {
super(brand, color);
this.seats = seats;
}
public void showCar() {
super.showinfo();
System.out.println("座位: " + seats + " 个");
}
}
public class Truck extends Vehicles {
private float load;
public Truck(String brand, String color, float load) {
super(brand, color);
this.load = load;
}
public void showTruck() {
super.showinfo();
System.out.println("载重 :" + load + "吨");
}
}
public class Test {
public static void main(String[] args) {
Vehicles vehicle = new Vehicles("奥迪", "黑色");
vehicle.showinfo();
Car car = new Car("桑塔纳", "红色", 5);
car.showCar();
Truck truck = new Truck("解放", "蓝色", 10);
truck.showTruck();
}
}