繁体   English   中英

使用“ this”关键字是否多余? Java的

[英]Is the use of the “this” keyword superfluous? Java

我一直在互联网上和那里进行一些研究,我想我几乎可以理解this关键字的工作方式。 我的问题是: this什么时候是必要的功能?

我知道,区分对象的私有实例变量和设置为完全相同名称的另一个变量很有用。 例:

public class SomeObject {
    private int someNum;
    public SomeObject() {}
    public setSomeNum(int someNum) {
        this.someNum = someNum;
    }
}

我还从第二个答案@ using-the-wordword-this-in-java中得知,它用于访问“嵌套”类。 尽管我还没有尝试过,但这似乎是一个很酷的主意。

这个问题是如何发生的:我正在编写一个classclass通过一系列属性定义游戏角色:

public class Charact {
    private String name;
    // A ton of other private variables that represent character stats.
    public Charact() {} // This one is for the main character.
    public Charact(String name, /*All of the other variable parameters*/) { // This one is used for making NPCs.
        this.name = name;
        // Setting of all of the other variables.
    }    
    public String getName() {return name;}
    public void setName(String name) {this.name = name;}
    // All of the other getter and setter methods.
}

因此,这里有一些关于我的代码的问题(与我的最初问题相切):

正在使用this调用setter方法,例如this.setVariable(variable); ,是多余的,因为它将执行与setVariable(variable);相同的setVariable(variable);

我专门用大写字母声明了所有私有实例变量,从而避免了在setter中使用this 我这样做(我是否违反了任何常规的命名约定?)还是应该在设置器中使用小写的变量名,而this应该对吗?

使用this是否有助于识别正在引用的类的实例,或者该实例已被计算机隐含,这意味着确实不需要this实例?

任何可以提供详尽阐述的答案都将非常有帮助,因为我上周才开始制作非静态课程。 另外,这是我的第一个问题,因此,如果不是真的使用正确的格式询问它,我将感到抱歉。

我认为您已经了解了this的用途。 当您需要明确说明所指的内容时,可以使用它。

这是一个新颖的例子。 (实际上并没有编写这样的类。它只是用来显示this用法。)

class Outer {
    int value; /* #1 */

    class Inner {
        int value; /* #2 */

        void setInnerValue(int value /* #3 */) {
            //    #2      #3
            //   vvvvv   vvvvv
            this.value = value;
        }

        void setOuterValue(int value /* #4 */) {
            //          #1      #4
            //         vvvvv   vvvvv
            Outer.this.value = value;
        }
    }
}

如果不需要限定您所引用的内容,那么是多余的。

this也用于调用链中的构造函数。

class Example {
    Example() { this(1); }
    Example(int i) { }
}

我违反任何常规的命名约定吗?

是的,你是。 Java中的标识符按惯例以小写字母开头(除非它们是static final常量,通常都是大写的)。 您应该遵循约定。

this.setVariable(variable)这样,用this调用setter方法通常是多余的,但却是很好的实践。

用大写字母声明任何变量会使所有可能不得不维护您的代码的所有其他Java程序员感到困惑。 我们采用惯例是有充分理由的。 当所有变量看起来都像类时,它最终也会使您感到困惑,并且您无法从实例化中分辨出静态调用。

this暗含了this object

编辑:以上句子已从this class更改

使用它很方便,因为稍后您将拥有诸如super之类的东西。 如果您不在那里使用super并且不使用它,那么您将得到混乱的代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM