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

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

问题描述

我的老师说,当我尝试访问方法中的实例变量时,我应该始终使用 this 关键字,否则我会执行双重搜索.局部范围搜索,然后是实例范围搜索.

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.

推荐答案

否,仅当您有名称冲突时才使用 this,例如当方法参数与实例字段具有相同名称时正在设置中.

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天全站免登陆