JAvaコンストラクション関数の例(コンストラクションメソッド)

1460 ワード

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~~~~
");
    }  

    void showMessage() {
        System.out.printf(" :%s, :%s
", 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~~~~
");
    }  

    void showMessage() {
        System.out.printf(" :%s, :%s
", color, brand);
    }  
}