First, define a class, named car, to achieve the following two construction methods:
1 Public classCar {2 3 //here is a constructor method that cannot have a return value type,4 PublicCar () {5 6System.out.println ("Car constructor-no arguments");7 8 }9 Ten //Here is also a construction method, with the method of constructing a parameter One PublicCar (String p_message) { ASYSTEM.OUT.PRINTLN ("car's constructor-parameter is:" +p_message); - } - the}
The above code should pay attention to:
1. The name and class name of the constructor method must be the same.
2. The constructor method is not a return value type, and cannot be used with the static modifier.
The following is the code for the subclass:
1 Public classAudiextendscar{2 3 PublicAudi () {4 //TODO auto-generated Constructor stub5SYSTEM.OUT.PRINTLN ("The construction method of Audi-no reference");6 }7 8 PublicAudi (intP_wheel) {9 Ten } One A}
The above code needs to be noted:
1. Subclasses inherit only the default constructor method of the parent class.
Then write a test master method, as follows:
1 Public classMaintest {2 3 /**4 * @paramargs5 */6 Public Static voidMain (string[] args) {7 //TODO auto-generated Method Stub8 9Audi A3 =NewAudi ();Ten audi a4 = new Audi (4); One A } - -}
The result after running the code is:
The constructor of car-the construction method of no parameter Audi -no parameter
Car's constructor-no parameters
Audi's construction method-with parameters: 4
So here's a conclusion:
The main function of the construction method is to complete the initialization of the object, which can pass the parameters that define the object to the domain of the object.
When you create an object, you first call the parent class default constructor to initialize the object, and then call the child class's own defined constructor.
How to construct in Java