TestCar.java
複製代碼代碼如下:
public class TestCar {
public static void main(String[] args) {
Car c1 = new Car();
c1.color = "red";
c1.brand = "xxx";//如果這輛車有很多屬性,這樣一一賦值不是很麻煩?有沒有辦法一生產出來就設定它的屬性(初始化)嗎?有~~~看下面
}
}
class Car {
String color;
String brand;
void run() {
System.out.printf("I am running...running..running~~~~/n");
}
void showMessage() {
System.out.printf("汽車顏色:%s, 汽車品牌:%s/n", color, brand);
}
}
改進後的TestCar_EX.java
複製代碼代碼如下:
/*什麼是建構方法*/
public class TestCar_EX {
public static void main(String[] args) {
Car c1 = new Car("red", "xxx");
}
}
class Car {
String color;
String brand;
public Car(String color, String brand) {
this.color = color; //這裡的this是這個物件的意思。第一個color是這個物件的color屬性,第二個是局部變數color
this.brand = brand; //同上
}
void run() {
System.out.printf("I am running...running..running~~~~/n");
}
void showMessage() {
System.out.printf("汽車顏色:%s, 汽車品牌:%s/n", color, brand);
}
}