繁体   English   中英

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

[英]Using this() of a constructor to call another constructor in the same class in Java

一小段测试代码如下:

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")我不知道其原理。 需要你的帮助。

Java文档说

如果存在,则另一个构造函数的调用必须是该构造函数的第一行。

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

原理是

如果存在,则另一个构造函数的调用必须是该构造函数的第一行。

参考: JavaDoc

使用this关键字,您正在调用其他构造函数。 当您注释掉第一条语句时,构造函数调用将成为合法的第一行。

调用this()时,您无法访问字段nameage 字段尚未初始化。 如果您希望名称默认为“ A”,年龄为20,则直接将值作为this()参数输入。

以下类将编译:

class Teacher {
    private String title;
    String name;
    int age;

    Teacher (String title) {
        this("A",20,title);
    }

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM