類與物件練習一 :請定義一個交通工具(Vehicle)的類
課堂練習1:
請定義一個交通工具(Vehicle)的類,其中有:
1. 屬性:速度(speed),體積(size)等
2.方法:移動(move()),設定速度(setSpeed(int speed)),設定體積(setSize(int size))加速speedUp(),減速speedDown()等
在測試類Vehicle中的main()中例項化一個交通工具物件,通過方法給它初始化speed,size的值,並打印出來。另外,呼叫加速,減速的方法對速度進行改變。
1.程式碼
(1)主類 TestVehicle.java
import java.util.Scanner;
public
public static void main(String[]args) {
Scanner sc=new Scanner(System.in); //建立物件sc
int sp=sc.nextInt(); //輸入速度sp的值
int si=sc.nextInt(); //輸入體積si的值
Vehicle car=new Vehicle(); //建立交通工具物件car
car.setSpeed(sp); //呼叫setSpeed方法,給速度賦值
car.setSize(si); //呼叫setSize方法,給體積賦值
car
System.out.print("汽車的速度增加了:");
int up=sc.nextInt(); //輸入速度增加的值
car.speedUp(car,up); //呼叫speedUp方法,輸出速度增加後的值
System.out.print("汽車的速度減少了:");
int down=sc.nextInt(); //輸入速度減少的值
car.speedDown(car,down); //呼叫speedDown方法,輸出速度減少之後的值
}
}
(2)類 Vehicle.java
public class Vehicle {
int speed;
int size;
int up;
int down;
void move() {//定義方法move
}
void setSpeed(int sp ) {//定義方法setSpeed ,為speed賦值
speed=sp;
}
void setSize(int si) {//定義方法setSize,為size賦值
size=si;
}
void printvehicle() {//定義方法printvehicle,輸出汽車速度和體積
System.out.println("汽車的速度為"+speed+"千米/時");
System.out.println("汽車的體積為"+size+"立方米");
}
void speedUp(Vehiclecarr,int upp) {//定義方法speedUp,輸出加速後的速度
up=carr.speed+upp;
System.out.println("汽車加速後的速度為:"+up+"千米/時");
}
void speedDown(Vehiclecarr,int downn) {//定義方法speedDown,輸出減速後的速度
down=carr.speed-downn;
System.out.println("汽車減速後的速度為:"+down+"千米/時");
}
}
2.執行截圖