首页 > 技术文章 > this 关键字的使用及说明

hs2018 2018-12-24 13:40 原文

this 是Java 中常见的一个关键字,它的主要作用是引用类的当前实例,本篇文章主要介绍 this 关键字的几种使用情况。

1. this 调用当前类的变量,也就是类中的成员变量。

代码示例:

public class Student {

    private String name="张三";

    public void testName(String name){
        System.out.println("局部变量name的值为:" + name);
        System.out.println("成员变量name的值为:" + this.name);
    }

}

 

public static void main(String[] args) {

        Student student = new Student();
        student.testName("李四");

    }

运行结果:

局部变量name的值为:李四
成员变量name的值为:张三

 

2. this 调用当前类的其它方法,也就是类中的成员方法。

代码示例:

public class Student {

    private String name="张三";

    public void testName(){
        this.haha();
    }

    public void haha(){
        System.out.println(" this 调用当前类的其它方法 ");
    }

}

 

public static void main(String[] args) {

        Student student = new Student();
        student.testName();

    }

运行结果:

 this 调用当前类的其它方法 

 

3. this 调用当前类的构造方法。

当使用 this 关键字在当前类的构造器中调用当前类的其它构造方法时,this 需要放在当前构造器的首行,不然会编译报错。

代码示例:

public class Student {

    public Student(){
        System.out.println("构造方法一");
    }

    public Student(String name){
        this();   //放在首行
        System.out.println("构造方法二");
    }

}

 

public static void main(String[] args) {

        Student student = new Student("张三");

    }

运行结果:

构造方法一
构造方法二

如果 this 不放在首行,编译期将会报错。

 

如果在当前类的普通方法中使用 this 调用类的构造器,同样会报错。

 

 

一些其它说明:

this 不能用在 static 修饰的方法中,因为被 static 修饰的方法属于类,不属于这个类的某个对象,而 this 代表当前类对象的引用,指向一个具体的对象。

推荐阅读