首页 > 编程笔记

Java this用法详解

this 是 Java 中的一个关键字,代表某个对象,其本质是“创建好的对象的地址”。

关键字 this 可以在实例方法中使用。由于在调用构造方法前,在运算符 new 的作用下已经创建对象,因此在构造方法中也可以使用关键字 this 来代表“当前对象”。

关键字 this 常见的用法如下:
第一种用法的示意图如下图所示:


图 1 第一种用法的示意图

【实例】关键字 this 的应用。
class Student { 
    // 成员变量 
    int sid; 
    String sname; 
 
    // 显式定义默认的构造方法 
    Student() { 
    } 
 
    // 带两个参数的构造方法 
    public Student(int sid, String sname) { 
        System.out.println("初始化已经建好的对象:" + this); // 使用this引用当前对象 
        this.sid = sid; // 使用this区分成员变量sid和参数sid 
        this.sname = sname; // 使用this区分成员变量sname和参数sname 
    } 
 
    public void login() { 
        // 使用this引用当前对象,但在这个上下文中可以省略 
        System.out.println(this.sname + "登录系统"); 
    } 
}
public class Test { 
    public static void main(String[] args) { 
        // 创建Student对象 
        Student student = new Student(1234, "changsheng"); 
        System.out.println("student 对象的引用:" + student); // 打印对象引用 
        student.login(); // 调用login方法 
    }
}
运行结果如下图所示:

初始化已经建好的对象:Student@75a1cd57
student 对象的引用:Student@75a1cd57
changsheng登录系统


第二种用法的示意图如下:


图 2 第二种用法的示意图

【实例】使用 this() 调用重载构造方法。
class Student { 
    int sid; 
    String sname; 
    String address; 
 
    Student() { 
    } 
 
    // 带两个参数的构造方法 
    public Student(int sid, String sname) { 
        System.out.println("初始化已经建好的对象:" + this); 
        this.sid = sid; 
        this.sname = sname; 
    } 
 
    // 带3个参数的构造方法 
    public Student(int sid, String sname, String address) { 
        // 下面一行代码通过this()调用带两个参数的构造方法,并且必须位于第一行 
        this(sid, sname); 
        this.address = address; 
    } 
 
    public void login() { 
        // 下面一行代码中的this代表调用此方法的对象,此处可以省略 
        System.out.println("学号:" + this.sid); 
        System.out.println("姓名:" + this.sname); 
        System.out.println("地址:" + this.address); 
    }  
}
public class Test { 
    public static void main(String[] args) { 
        // 创建Student对象 
        Student student = new Student(1234, "changsheng", "China"); 
        student.login(); 
    } 
}
运行结果为:

初始化已经建好的对象:Student@75a1cd57
学号:1234
姓名:changsheng
地址:China

推荐阅读