JAVA this()方法

this() 访问构造方法

this() 用来访问本类的构造方法,括号中可以有参数,如果有参数就是调用指定的有参构造方法。

例子

下面定义一个 Student 类,使用 this() 调用构造方法给 name 赋值,Student 类的代码如下所示:

public class Student {
    String name;
    // 无参构造方法(没有参数的构造方法)
    public Student() {
        this("韩梅梅");//调用了Student(String name)构造方法
    }
    // 有参构造方法
    public Student(String name) {
        this.name = name;
    }
    // 输出name和age
    public void print() {
        System.out.println("姓名:" + name);
    }
    public static void main(String[] args) {
        Student stu = new Student();
        stu.print();
    }
}

输出结果为:

姓名:韩梅梅

注意:

  • this() 不能在普通方法中使用,只能写在构造方法中

  • 在构造方法中使用时,必须是第一条语句。


原文出处:/show_1IX10Ern0ZrH.html