Construction method
There is a special member method in each Java class, and its method name is consistent with the class name . When creating an object, call this special method to initialize member variables, this method is called a constructor.
Notice
The format of creating a constructor method is the same as that of creating a member method, but the following points should be noted:
- 1. The name of the constructor is the same as the class name of the class to which it belongs
- 2. The construction method is to assign an initial value to the object and has no return value
- 3. The construction method cannot be explicitly called by the program, but is automatically called by the system when new constructs the object
- 4. A constructor can have zero or more formal parameters
- 5. The construction method can be defined by the user in the class. If the user does not define it, the system will automatically generate an empty construction method
- 6. The constructor can implement different initialization methods through overloading
The format of the constructor
The format for creating a constructor is:
Format 1: No parameter construction method
access control class name () { constructor body }
Format 2: Constructor method with parameters
Access control class name (type 1 parameter 1[, type 2 parameter 2,...] )
{ constructor body }
Example program to initialize object properties using constructor:
package test;
public class Person {
String name;
int age;
public Person(String str, int a){
name = str;
age = a;
}
public void say(){
System.out.println("姓名:"+name+",年龄:"+age);
}
}
package test;
public class JavaDemo {
public static void main(String[] args) {
Person p1 = new Person("adili",20);
p1.say();
}
}