I. construction method
Function: assign value to member variable while new, and initialize the attribute of the object
Format:
Permission method name (parameter list){
}
The name of the method must be exactly the same as the name of the class, and the case must be the same
Constructor cannot write return value type, such as void,int
The construction method is executed automatically on new, only once
Code: Person class (including this usage introduction)
1 public class Person {
2 private String name;
3 private int age;
4
5 /*
6 * this Usage
7 * 1. this.To distinguish the problem of the same name of a local variable and a member variable. Followed by member variable
8 * 2. this Between construction methods, this()
9 *
10 */
11
12 public Person(String name,int age){
13 //System.out.println("With parameters");
14 this.name = name;
15 this.age = age;
16
17 }
18
19 //Overloaded construction method, empty parameter construction method
20 public Person(){
21 //this()It must be placed in the first line of the construction method to call the construction method with parameters
22 /*this("Li Si, "20";
23 System.out.println("The construction method of null parameter ');*/
24
25 System.out.println("Construction method of parent class");
26 }
27
28 public String getName() {
29 return name;
30 }
31 public void setName(String name) {
32 this.name = name;
33 }
34 public int getAge() {
35 return age;
36 }
37 public void setAge(int age) {
38 this.age = age;
39 }
40 }
II. super() usage
In the subclass, super() calls the construction method of the parent class
super() calls the null parameter constructor of the parent class
Super (parameter) calls the parameter construction method of the parent class
Note: no matter how many construction methods are overloaded, the first line must be super()
Constructor not overridden
this() and super() cannot exist in a constructor at the same time
All constructors of a subclass must be called directly or indirectly to the parent constructor
Subclass construction method, write nothing, the first line of the default construction method super();
Code: Student class
1 public class Student extends Person{
2 public Student(){
3 this("222",2);
4
5 }
6
7 public Student(String s,int a){
8 super("111",1);
9 }
10 }