我应该使用“这个”吗?我想在方法中引用实例变量的关键字? [英] Should I use "this" keyword when I want to refer to instance variables within a method?

查看:137
本文介绍了我应该使用“这个”吗?我想在方法中引用实例变量的关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的老师说当我尝试访问方法中的实例变量时,我应该总是使用这个关键字,否则我会执行双重搜索。本地范围搜索,然后是实例范围搜索。

My teacher says that when I try to access an instance variable within a method I should always use the this keyword, otherwise I would perform a double search. A local scope search and then an instance scope search.

示例:

public class Test(){
    int cont=0;
    public void Method(){
        System.out.println(cont);//Should I use This.cont instead?
    }
}

我希望他错了,但我不能找到任何参数。

I hope he is wrong, but I can't find any argument.

推荐答案

不,只有当你有这个时名称冲突,例如当一个方法参数与它正在设置的实例字段同名时。

No, only use this when you have a name conflict such as when a method parameter has the same name as an instance field that it is setting.

它可以在其他时间使用,但我们很多人都觉得它只是为代码增加了不必要的措辞。

It can be used at other times, but many of us feel that it simply adds unnecessary verbiage to the code.

这篇关于我应该使用“这个”吗?我想在方法中引用实例变量的关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆