(OJ)Java⾯向对象-编写汽车类
编写汽车类
Problem Description
1.实验⽬的
(1) 熟悉类的创建⽅法
(2) 掌握对象的声明与创建
(3) 能利⽤⾯向对象的思想解决⼀般问题
2.实验内容
编写⼀个java程序,设计⼀个汽车类Vehicle,包含的属性有车轮的个数wheels和车重weight。⼩汽车类Car是Vehicle的⼦类,包含的属性有载⼈数loader。卡车类Truck是Car类的⼦类,其中包含的属性有载重量payload。每个类都有构造⽅法和输出相关数据的⽅法。
3.实验要求
补充完整下⾯的代码
public class Main{
public static void main(String[] args){
Vehicle v=new Vehicle(8,10.00);
smallCar c=new smallCar(6);
Truck t=new Truck(10);
v.disMessage();
c.disM();
t.disM2();
t.disM3();
}
}
// 你的代码
Output Description
The number of wheels in this car is 8, weight is 10.0
This car can carry 6 persons
The load of this truck is 10
The number of wheels in this truck is 8, weight is 10.0, can carry 6 persons, load of this truck is 10
解题代码
// Vehicle 类
class Vehicle{
// wheels 车轮个数
public int wheels;
// 重量
public double weight;
// 带参构造⽅法
public Vehicle(int wheels,double weight){
this.wheels = wheels;
this.weight = weight;
}
// ⽆参构造⽅法
public Vehicle(){
}
/
/ 打印信息
public void disMessage(){
System.out.println("The number of wheels in this car is "+ wheels +", weight is "+ weight);
}
}
// smallCar类继承Vehicle类
class smallCar extends Vehicle{
class smallCar extends Vehicle{
// loader 载⼈数
public int loader;
// 带参构造三个参数
public smallCar(int wheels,double weight,int loader){
// 调⽤⽗类构造器
super(wheels, weight);
this.loader = loader;
}
// 带参构造⼀个参数
public smallCar(int loader){
// 调⽤⽗类构造根据题⽬输出 wheels = 8 weight10.00
super(8,10.00);
this.loader = loader;
}
/
/ ⽆参构造
public smallCar(){
}
// 打印信息
public void disM(){
System.out.println("This car can carry "+ loader +" persons");
}
}
// Truck类继承smallCar类
class Truck extends smallCar{
// payload 载重量
private int payload;
// 带参构造⼀个参数
public Truck(int payload){
// 调⽤⽗类构造根据题⽬输出 loader = 6
super(6);
this.payload = payload;
}
// 带参构造四个参数
public Truck(int wheels,double weight,int loader,int payload){
// 调⽤⽗类构造
super(wheels, weight, loader);
java怎么编写this.payload = payload;
}
// ⽆参构造
public Truck(){
}
// 打印信息
public void disM2(){
System.out.println("The load of this truck is "+ payload);
}
// 打印信息
public void disM3(){
System.out.println("The number of wheels in this truck is "+ wheels +", weight is "+ weight +", can carry "+ loader +" persons, load of this truck is " + payload);
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。