當前位置:才華齋>計算機>java語言>

java建構函式實現程式碼示例

java語言 閱讀(1.16W)

java建構函式實現程式碼示例

複製程式碼 程式碼如下:

public class TestCar {

public static void main(String[] args) {

Car c1 = new Car();

r = "red";

d = "xxx";//如果這輛汽車有很多屬性,這樣一一賦值不是很麻煩?有沒有辦法一生產出來就設定它的屬性(初始化)嗎?有~~~看下面

}

}

class Car {

String color;

String brand;

void run() {

tf("I am ing~~~~n");

}

void showMessage() {

tf("汽車顏色:%s, 汽車品牌:%sn", color, brand);

}

}

改進後的Car_

複製程式碼 程式碼如下:

/*什麼是構造方法*/

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) {

r = color; //這裡的this是這個物件的意思.第一個color是這個物件的color屬性,第二個是區域性變數color

d = brand; //同上

}

void run() {

tf("I am ing~~~~n");

}

void showMessage() {

tf("汽車顏色:%s, 汽車品牌:%sn", color, brand);

}

}