1编写一个Java程序,设计一个汽车抽象类Vehicle,包含的属性有车 轮个数wheels和车重weight。小车类Car是Vehicle的子类,其中 包含的属性有载人数loader。卡车类Truck是Car类的子类,其中 包含的属性有载重量payload (1)每个类都有构造方法进行属性初始化: (2)抽象类Vehicle类具有输出相关数据信息的抽象方法; (3)CarTruck子类覆写抽象类的抽象方法,并给子类分别添加 一个子类特有的方法(内容自定); (4)使用Test类中的main方法实例化Car,Truck,并输出相关信 息(分别练习向上转型和向下转型)。
时间: 2023-06-20 11:07:40 浏览: 385
代码如下:
```java
// Vehicle.java
public abstract class Vehicle {
protected int wheels;
protected double weight;
public Vehicle(int wheels, double weight) {
this.wheels = wheels;
this.weight = weight;
}
public abstract void printInfo();
}
// Car.java
public class Car extends Vehicle {
private int loader;
public Car(int wheels, double weight, int loader) {
super(wheels, weight);
this.loader = loader;
}
@Override
public void printInfo() {
System.out.println("This is a car with " + wheels + " wheels, weighs " + weight + "kg, and can carry " + loader + " passengers.");
}
public void drive() {
System.out.println("The car is driving.");
}
}
// Truck.java
public class Truck extends Car {
private double payload;
public Truck(int wheels, double weight, int loader, double payload) {
super(wheels, weight, loader);
this.payload = payload;
}
@Override
public void printInfo() {
System.out.println("This is a truck with " + wheels + " wheels, weighs " + weight + "kg, can carry " + loader + " passengers, and can transport " + payload + "kg of goods.");
}
public void transport() {
System.out.println("The truck is transporting goods.");
}
}
// Test.java
public class Test {
public static void main(String[] args) {
Vehicle v1 = new Car(4, 1000, 5);
Vehicle v2 = new Truck(6, 5000, 2, 10000);
v1.printInfo();
if(v1 instanceof Car) {
((Car) v1).drive();
}
System.out.println();
v2.printInfo();
if(v2 instanceof Truck) {
((Truck) v2).transport();
}
}
}
```
输出结果如下:
```
This is a car with 4 wheels, weighs 1000.0kg, and can carry 5 passengers.
The car is driving.
This is a truck with 6 wheels, weighs 5000.0kg, can carry 2 passengers, and can transport 10000.0kg of goods.
The truck is transporting goods.
```
在这个例子中,我们定义了一个抽象类 Vehicle,它有两个属性 wheels 和 weight,并且声明了一个抽象方法 printInfo。Car 和 Truck 类分别继承了 Vehicle 类,它们都有一个特定的属性,即 Car 类的 loader 和 Truck 类的 payload。这两个子类分别实现了 printInfo 方法,并且分别添加了一个特有的方法:Car 类的 drive 方法和 Truck 类的 transport 方法。
在 Test 类的 main 方法中,我们创建了一个 Car 对象和一个 Truck 对象,并且分别调用了它们的 printInfo 方法。我们还使用了 instanceof 运算符来判断一个对象是否是某个类的实例,然后进行向下转型,并调用特有的方法。