2、请定义一个交通工具(Vehicle)的类
其中有属性:
速度〈speed)
休积(size)等等
方法移动(move())
设置速度:(setSpeed(int speed))
减速speedDown()等等
最后在测试类Vehicle中的main()中实例化一个交通工具对象
并通过方法给它初始化speed,size的值并且打印出来。
另外调用加速减速的方法对速度进行改变。
public class HomeWork2 {
//最后在测试类Vehicle中的main()中实例化一个交通工具对象
//并通过方法给它初始化speed,size的值并且打印出来。
//另外调用加速减速的方法对速度进行改变。
public static void main(String[] args) {
//新建交通工具对象
Vehicle car = new Vehicle("汽车");
car.move();
car.setSpeed(80);
car.setSize(10);
System.out.println(car.name +"的速度为:" + car.getSpeed() + "KM/h");
System.out.println(car.name +"的体积为:" + car.getSize() + "M^3");
//调用加速方法
car.speedUp(10);
System.out.println(car.name +"的速度为:" + car.getSpeed() + "KM/h");
//查看加速边界值
car.speedUp(100);
System.out.println(car.name +"的速度为:" + car.getSpeed() + "KM/h");
//调用减速方法
car.speedDown(20);
System.out.println(car.name +"的速度为:" + car.getSpeed() + "KM/h");
//查看减速边界值
car.speedDown(200);
System.out.println(car.name +"的速度为:" + car.getSpeed() + "KM/h");
}
}
class Vehicle {
//速度
private int speed;
//体积
private int size;
//交通工具名称
public String name;
//无参构造
public Vehicle() {
}
//有残构造
public Vehicle(int speed, int size) {
this.speed = speed;
this.size = size;
}
//有参构造2
public Vehicle(String name) {
this.name = name;
}
//getting and setting
public int getSpeed() {
return speed;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
//移动方法
public void move() {
System.out.println(name + "正在移动!");
}
//设置速度方法
public void setSpeed(int speed) {
this.speed = speed;
}
public void speedUp(int addSpeed) {
if(this.speed >= 120 || (this.getSpeed() + addSpeed) >= 120){
System.out.println("根据交通规则,当前速度无法超过120KM/h");
this.speed = 120;
}else
this.setSpeed(this.getSpeed() + addSpeed);
}
//减速方法
public void speedDown(int subSpeed) {
if(this.speed < subSpeed || this.speed == 0) {
System.out.println(name + "停止移动!");
this.speed = 0;
}else
this.setSpeed(this.getSpeed() - subSpeed);
}
}