The Java constructor example of the of constructor
- 2020-04-01 03:11:22
- OfStack
TestCar. Java
public class TestCar {
public static void main(String[] args) {
Car c1 = new Car();
c1.color = "red";
c1.brand = "xxx";//If the car has a lot of properties, wouldn't it be too much trouble to assign them all? Is there a way to set its properties as soon as it is produced? There's ~~~ look below & NBSP;
}
}
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 :%sn", color, brand);
}
}
Improved 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; //The first color is the color property of the 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 :%sn", color, brand);
}
}