课后作业1
Vehiclel类代码:
public class Vehicle {
private String brand;
private String color;
private double speed;
public Vehicle(String brand,String color){
this.brand = brand;
this.color = color;
this.speed = 0;
}
public Vehicle(){
}
public String getBrand() {
return brand;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public double getSpeed() {
return speed;
}
public void setSpeed(double speed) {
this.speed = speed;
}
public void run(double num){
while(true){
// 用来显示循环间隔,车辆提速间隔时间
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(this.getSpeed()<num){
System.out.println("车辆正在提速,当前车速为"+this.getSpeed());
}else{
break;
}
this.setSpeed(this.getSpeed()+10);
}
System.out.println(this.getColor()+"色的"+this.getBrand()+"品牌的的汽车以"+this.getSpeed()+"的速度在行驶。");
}
}
Car类 代码:
class Car extends Vehicle {
private int loader;
public int getLoader() {
return loader;
}
public void setLoader(int loader) {
this.loader = loader;
}
public Car(String brand, String color, int loader) {
super(brand,color);
this.loader = loader;
}
public void run(double num){
while(true){
// 用来显示循环间隔,车辆提速间隔时间
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(this.getSpeed()<num){
System.out.println("车辆正在提速,当前车速为"+this.getSpeed());
}else{
break;
}
this.setSpeed(this.getSpeed()+10);
}
System.out.println(this.getColor()+"色的,载着"+this.getLoader()+"人的"+this.getBrand()+"品牌的的汽车以"+this.getSpeed()+"的速度在行驶。");
}
}
测试类VehicleTest类代码:
import java.util.Scanner;
public class VehicleTest {
public static void main(String[] args) {
System.out.println("请输入汽车行驶的速度……");
Scanner in = new Scanner(System.in);
double speed = in.nextDouble();
Vehicle v = new Vehicle("benz", "红");
v.run(speed);
Car car = new Car("honda","红",2);
car.run(speed);
}
}
执行结果: