gpt4 book ai didi

java - Java中使用构造函数的this()调用同一个类中的另一个构造函数

转载 作者:行者123 更新时间:2023-12-01 22:32:25 25 4
gpt4 key购买 nike

一小段测试代码如下:

class Teacher {
private String title;
String name = "A";
int age = 20;

Teacher (String title) {
//System.out.println(name);
this(name,age,title);
}

Teacher (String name, int age, String title) {
System.out.println("OK");
}
}

public class Test {
public static void main (String[] args) {
Teacher teacher1 = new Teacher("John");
Teacher teacher2 = new Teacher("Mike",25,"TA");
}
}

如上,我注释了System.out.println(name);,编译后,出现错误:Can't reference name(age) before the superclass constructor has been Called . 但是,我注释了 this(name,age,title);,这意味着我只使用了 System.out.println(name);。错误消失了。因此,我认为nameage已经初始化并得到值A20。也就是说,this(name,age,title)实际上是this("a",20,"John"),不知道原理。需要您的帮助。

最佳答案

当您链接构造函数调用时,this/super 构造函数调用必须是第一个语句。请参阅this了解详情。

关于java - Java中使用构造函数的this()调用同一个类中的另一个构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27460679/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com