java構造函數實現代碼示例

來源:文萃谷 1.08W

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

}

}

熱門標籤