java結構函數示例(結構辦法)。本站提示廣大學習愛好者:(java結構函數示例(結構辦法))文章只能為提供參考,不一定能成為您想要的結果。以下是java結構函數示例(結構辦法)正文
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);
}
}