为什么“this(实参列表)”和“super(实参列表)“不能同时存在于同一个构造方法中?”

核心:

  1. 在一个类中,不可能所有的构造方法中都存在“this(实参列表)”,因为构造方法不可递归。
  2. 也就意味着,在一个类中的所有构造方法中,肯定至少有一个构造方法中存在“super(实参列表)”。
  3. super(实参列表)的作用:保证子类对象操作父类成员变量之前,就已经完成了对父类成员变量的初始化操作。
  4. this(实参列表)的作用:保证父类初始化的唯一性。创建子类对象的过程中,子类构造方法中只会调用一次父类的构造方法。

父类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* 父类
*/
public class Person {
private String name;
private int age;

public Person() {
System.out.println("Person类的无参构造方法");
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}

子类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* 子类
*/
public class Student extends Person {
private double score;

public Student() {
//如果在子类构造方法中,我们没有显示的调用别的构造方法,那么默认就会调用父类的无参构造方法。
//super(); // 此处默认存在的语句,用于调用父类的无参构造方法。
System.out.println("Student类的无参构造方法");
}

public Student(String name, int age) {
//super(name, age);
this();
}

public Student(String name, int age, double score) {
//需求:在此处,我们需要调用父类的Person(String, int)构造方法,完成对name和age的指定初始化操作,并且也实现了代码的复用。
//原因:a)Person类的成员变量,则就应该调用Person类的构造方法来完成指定初始化,从而满足“自己的事,自己干”。
// b)成员变量一律私有化,这样能避免外界直接操作成员变量,想要操作成员变量则必须通过setter和getter方法来实现。
//super(name, age);
this(name, age);
/*this.name = name;
this.age = age;*/
this.score = score;
}

public double getScore() {
return score;
}

public void setScore(double score) {
this.score = score;
}

@Override
public String toString() {
return "Student{" +
"score=" + score +
"} " + super.toString();
}
}


测试类:

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* 测试程序
*/
public class Test01 {
public static void main(String[] args) {
/*Student stu = new Student();
System.out.println(stu);*/

// 实例化Student对象
Student stu = new Student("卧龙", 18, 100.0);
System.out.println(stu);
}
}