29.编写一个Java应用程序,设计一个汽车类Vehicle,包含的属性有车轮个数 wheels和车重weight。小车类Car是Vehicle的子类,其中包含的属性有载人数 loader。卡车类Truck是Car类的子类,其中包含的属性有载重量payload。每个 类都有构造方法和输出相关数据的方法。最后,写一个测试类来测试这些类的功 能。

时间:2021-10-19 16:29:11

//Vehicle类

package d922A;

public class Vehicle {

private int wheels;

private double weight;

Vehicle()

{

weight=1;wheels=4;

}

Vehicle(int lun, double zizhong)

{

wheels=lun;

weight=zizhong;

}

public int getWheels() {

return wheels;

}

public void setWheels(int wheels) {

this.wheels = wheels;

}

public double getWeight() {

return weight;

}

public void setWeight(double weight) {

this.weight = weight;

}

public void showData(){

System.out.println("*"+wheels+"个,"+"自重"+weight+"t");

}

}

// Car类

package d922A;

public class Car extends Vehicle {

private int loader;

Car()

{

loader=4;

}

Car(int zaikeshu)

{

loader=zaikeshu;

}

Car(int lun, double zizhong,int zaikeshu)

{

super(lun,zizhong);

loader=zaikeshu;

}

public void showData(){

System.out.println("*"+getWheels()+"个"+"自重"+getWeight()+"t");

System.out.println("载客人数:"+loader+"人");

}

public int getLoader() {

return loader;

}

public void setLoader(int loader) {

this.loader = loader;

}

}

// Truck类

package d922A;

public class Truck extends Car {

private double payload;

Truck()

{

payload=10;

}

Truck(double zaizhong)

{

payload=zaizhong;

}

Truck(int zaikeshu,double zaizhong)

{

super(zaikeshu);

payload=zaizhong;

}

Truck(int lun, double zizhong,int zaikeshu,double zaizhong)

{

super(lun,zizhong,zaikeshu);

payload=zaizhong;

}

public void showData(){

System.out.println("*"+getWheels()+"个"+"自重"+getWeight()+"t");

System.out.println("载客人数:"+getLoader()+"人");

System.out.println("载重:"+payload+"t");

}

}

//主类

package d922A;

public class Testvec {

public static void main(String[] args) {
Truck a=new Truck();
a.showData();
a=new Truck(50);
a.showData();
a=new Truck(2,50);
a.showData();
a=new Truck(8,3,4,100);
a.showData(); }

}

///运行结果

*4个自重1.0t

载客人数:4人

载重:10.0t

*4个自重1.0t

载客人数:4人

载重:50.0t

*4个自重1.0t

载客人数:2人

载重:50.0t

*8个自重3.0t

载客人数:4人

载重:100.0t