TestCar.java
Copy the code code as follows:
public class TestCar {
public static void main(String[] args) {
Car c1 = new Car();
c1.color = "red";
c1.brand = "xxx";//If this car has many attributes, wouldn't it be troublesome to assign values one by one like this? Is there a way to set its properties (initialize) as soon as it is produced? Yes~~~see below
}
}
class Car {
String color;
String brand;
void run() {
System.out.printf("I am running...running..running~~~~/n");
}
void showMessage() {
System.out.printf("Car color: %s, Car brand: %s/n", color, brand);
}
}
Improved TestCar_EX.java
Copy the code code as follows:
/*What is a construction method*/
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 here means the object. The first color is the color attribute of this object, and the second is the local variable color
this.brand = brand; //Same as above
}
void run() {
System.out.printf("I am running...running..running~~~~/n");
}
void showMessage() {
System.out.printf("Car color: %s, Car brand: %s/n", color, brand);
}
}