美文网首页
this关键字

this关键字

作者: _Dansh | 来源:发表于2017-07-07 17:53 被阅读0次

示例代码

给出方法test:

public class SimpleClass {
    public int a;
    public void test() {
        int a= 50;
        this.a= a+5;
    }
}

使用如下代码去测试test方法:

public class TestThis {
    public static void main(String[] args) {
        SimpleClass simple= new SimpleClass();
        simple.test();
        System.out.print("simple对象中的a值为:");
        System.out.print(simple.a)
    } 
}

则控制台输出如下内容:

simple对象中的a值为:55

规则

  • 方法中使用到的变量的寻找规律是先找局部变量,再找实例变量(若二者重名且没有使用this关键字
  • this关键字只能在方法中使用,用来调用实例变量。如果使用this关键字访问一个变量,java平台不会在局部变量中寻找,而是在实例变量中寻找
  • 只有局部变量与实例变量重名的情况下,才有使用this关键字的必要。但是为了让程序易读且减少错误,推荐使用this关键字

例如一个方法中本来没有与实例变量重名的局部变量,但是后来增加了一个与实例变量重名的局部变量,这就会让程序出现潜在的错误。

相关文章

网友评论

      本文标题:this关键字

      本文链接:https://www.haomeiwen.com/subject/tbkrhxtx.html