设计一个汽车类vehicle,包含的数据成员有车轮个数wheels和车重weight。小车类car是它的派生类,其中包含载人数passenge_load,卡车类Truck是Car类的子类,其中包含的属性有载重量payload。每个类都有相关数据的输出方法。在主程序中定义一个car类对象,对其车轮个数、车重、载人数进行设置并显示。
class vehicle
{
private int wheels;
private float weight;
vehicle(int wheels, float weight) {
wheel_load(wheels,weight);
get_wheels();
get_weight();
showInformation();
}
void wheel_load(int wheels, float weight) {
this.wheels = wheels;
this.weight = weight;
}
int get_wheels() {
return wheels;
}
float get_weight() {
return weight / wheels;
}
void showInformation() {
System.out.print("车轮:" + wheels + "个");
System.out.println(" 重量:" + weight + "公斤");
}
}
class car extends vehicle {
int passenger_load;
car(int wheels, float weight, int passengers) {
super(wheels, weight);
passenger_load = passengers;
get_passengers();
this.show();
}
int get_passengers() {
return passenger_load;
}
void show() {
System.out.print("车型:小车");
System.out.println(" 载人:" + passenger_load + "人"+"\n");
}
}
class truck extends vehicle {
int passenger_load;
float payload;
float weight;
truck(int wheels, float weight, int passengers, float max_load) {
super(wheels, weight);
this.weight = weight;
this.passenger_load=passengers;
this.payload=max_load;
get_passengers();
efficiency();
show();
}
int get_passengers() {
return passenger_load;
}
float efficiency() {
return payload / (payload + weight);
}
void show() {
System.out.print("车型:卡车");
System.out.print(" 载人:" + passenger_load + "人");
System.out.println(" 效率:" + efficiency()+"\n");
}
}
public class Test {
public static void main(String[] args) {
car car1 = new car(4, 2000, 5);
truck tru1= new truck (10, 8000, 3, 340000);
System.out.println("输出结果:");
car1.show();
tru1.show();
}
}
本文介绍了一个基于面向对象编程的汽车类设计案例,包括基本的Vehicle类,派生的Car类和Truck类。Vehicle类包含车轮数量和车重属性,Car类增加了载人数属性,而Truck类则进一步引入了载重量属性。每个类都实现了显示自身信息的方法。
1万+

被折叠的 条评论
为什么被折叠?



