课堂练习1:
请定义一个交通工具(Vehicle)的类,其中有:
属性:速度(speed),体积(size)等
方法:移动(move()),设置速度(setSpeed(int speed)),设置体积(setSize(int size))加速speedUp(),减速speedDown()等
在测试类Vehicle中的main()中实例化一个交通工具对象,通过方法给它初始化speed,size的值,并打印出来。另外,调用加速,减速的方法对速度进行改变。
1.代码
(1)Vehicle.java
public class Vehicle {
int speed;
int size;
public void move() {
}
public int setSpeed(int speed) {
return speed;
}
public int setSize(int size) {
return size;
}
public int speedUp(int now,int speedUp) {
int newSpeed=now+speedUp;
return newSpeed;
}
public int speedDown(int now,int speedDown) {
int newSpeed=now-speedDown;
return newSpeed;
}
}
(2)Test.java
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub v
Vehicle car=new Vehicle();
car.speed=car.setSpeed(60);
car.size=car.setSize(8);
System.out.println("小轿车的体积为"+car.size+"立方米,速度为"+car.speed+"Km/h。");
int speedUp=car.speedUp(car.speed,6);
System.out.println("加速后小轿车的速度为"+speedUp+"Km/h。");
int speedDown=car.speedDown(speedUp,8);
System.out.println("减速后小轿车的速度为"+speedDown+"Km/h。");
}
}
2.运行截图