(1)编写一个Java应用程序,设计一个汽车类Vehicle,包含的属性有车轮个数wheels和车重weight。
(2)小车类Car是Vehicle的子类,其中包含的属性有载人数loader。
(3)卡车类Truck是Car类的子类,其中包含的属性有载重量payload。
(4)每个类都有构造方法和输出相关数据的方法show。
(5)编写测试类进行多态性测试。
以下代码用两种方式实现代码类实现方式一:
public class VehicleTest {
public static void showInfo(Vehicle v) {
v.show();
}
public static void main(String[] args) {
Car c = new Car(4, 100, 20);
Truck t = new Truck(14, 1100, 120, 1200);
System.out.println("---------------输出Car的信息---------------");
showInfo(c);
System.out.println("---------------输出Truck的信息---------------");
showInfo(t);
}
}
class Vehicle {
int wheels;
double weight;
public Vehicle(int wheels, double weight) {
this.wheels = wheels;
this.weight = weight;
}
public void show() {
System.out.println("车轮数:" + wheels);
System.out.println("车重:" + weight);
}
}
class Car extends Vehicle {
int loader;
public Car(int wheels, double weight, int loader) {
super(wheels, weight);
this.loader = loader;
}
public void show() {
super.show();
System.out.println("载人数:" + loader);
}
}
class Truck extends Car {
double payload;
public Truck(int wheels, double weight, int loader, double payload) {
super(wheels, weight, loader);
this.payload = payload;
}
public void show() {
super.show();
System.out.println("载重量:" + payload);
}
}
代码类实现方式二:
public class VehicleTest1 {
public static void main(String[] args) {
Vehicle c = new Car(4, 100, 20);
Vehicle t = new Truck(14, 1100, 120, 1200);
System.out.println("---------------输出Car的信息---------------");
c.show();
System.out.println("---------------输出Truck的信息---------------");
t.show();
}
}
class Vehicle {
int wheels;
double weight;
public Vehicle(int wheels, double weight) {
this.wheels = wheels;
this.weight = weight;
}
public void show() {
System.out.println("车轮数:" + wheels);
System.out.println("车重:" + weight);
}
}
class Car extends Vehicle {
int loader;
public Car(int wheels, double weight, int loader) {
super(wheels, weight);
this.loader = loader;
}
public void show() {
super.show();
System.out.println("载人数:" + loader);
}
}
class Truck extends Car {
double payload;
public Truck(int wheels, double weight, int loader, double payload) {
super(wheels, weight, loader);
this.payload = payload;
}
public void show() {
super.show();
System.out.println("载重量:" + payload);
}
}
效果类实现:



