2.请定义一个交通工具(Vehicle)类,其具有的属性和方法如下:
属性:
1)速度-speed;2)长度-length;3)宽度-width; 4)高度-height;
方法:
1)移动-move()
2)加速-speedUp(int num)
num:表示在当前速度上增加的速度值
3)减速-speedDown(int num)
num:表示在当前速度上减低的速度值
4)对Vehicle 类的各个内部字段使用 setter/getter进行封装
5)创建测试代码,设置输出一个Vehicle对象的各个属性,并测试speedUp() 和 speedDown()方法。
public class Vehicle {
private double speed;
private double length;
private double width;
private double height;
public Vehicle(double speed, double length, double width, double height) {
this.speed = speed;
this.length = length;
this.width = width;
this.height = height;
}
public void move() {
System.out.println("Vehicle is moving.");
}
public void speedUp(double num) {
speed += num;
System.out.printf("Vehicle speed increased by %.2f. Current speed: %.2f \n", num, speed);
}
public void speedDown(double num) {
speed -= num;
if (speed < 0) {
speed = 0;
}
System.out.printf("Vehicle speed decreased by %.2f. Current speed: %.2f \n", num, speed);
}
public void setSpeed(double speed) {
this.speed = speed;
}
public double getSpeed() {
return speed;
}
public void setLength(double length) {
this.length = length;
}
public double getLength() {
return length;
}
public void setWidth(double width) {
this.width = width;
}
public double getWidth() {
return width;
}
public void setHeight(double height) {
this.height = height;
}
public double getHeight() {
return height;
}
}
测试代码
public class VehicleTest {
public static void main(String[] args) {
Vehicle car = new Vehicle(50, 4.5, 2, 1.8);
System.out.printf("车速:%.2f km/h%n", car.getSpeed());
System.out.printf("车长:%.2f m%n", car.getLength());
System.out.printf("车宽:%.2f m%n", car.getWidth());
System.out.printf("车高:%.2f m%n", car.getHeight());
car.speedUp(10);
car.speedDown(5);
car.setLength(5);
car.setWidth(2.3);
car.setHeight(1.6);
System.out.printf("车长:%.2f m%n", car.getLength());
System.out.printf("车宽:%.2f m%n", car.getWidth());
System.out.printf("车高:%.2f m%n", car.getHeight());
}
}