java 构造函数中的Java“this”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4754237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 07:52:19  来源:igfitidea点击:

Java "this" in constructors

javaconstructor

提问by André Al?ada Padez

Well, this is a very basic question, I've never coded in java, but I'm writing a class for a friend... Having something like:

嗯,这是一个非常基本的问题,我从来没有用 Java 编码过,但我正在为朋友写一个类......有类似的东西:

class myClass{

    private string name;
    public string getName() {
        return this.name;
    }   
    public void setName (int newValue) {
        this.name = newValue;
    }

    private int number;
    public int getNumber() {
        return this.number;
    }   
    public void setNumber (int newValue) {
        this.number = newValue;
    }
}  

The way I was thinking of building the constructor was:

我考虑构建构造函数的方式是:

public myClass (string name, int numbers) {
    this.name = name;
    this.number = number;
}

My questions:

我的问题:

  1. I'm using the same identifiers for the properties as for the parameters. Does "this." avoid any trouble here?
  2. Is it better to use the set methods and, if so, should i use "this."?
  1. 我对属性使用与参数相同的标识符。做这个。” 避免这里的任何麻烦?
  2. 使用 set 方法是否更好,如果是,我应该使用“this.”吗?

Thank you very much

非常感谢你

回答by wmorrell

  1. Yes, it avoids the name clash. In the constructor's context, the name namerefers to the parameter, and the name this.namerefers to the instance field.
  2. Depends on what you mean by "better." Personally, I would make the nameand numberfields final, so the class is immutable. In my experience, it's better to start from an immutable class definition, and only move towards something mutable if there is a legitimate need to do so.
  1. 是的,它避免了名称冲突。在构造函数的上下文中,名称name指的是参数,而名称this.name指的是实例字段。
  2. 取决于你所说的“更好”是什么意思。就个人而言,我会将nameandnumber字段设为 final,因此该类是不可变的。根据我的经验,最好从不可变的类定义开始,并且只有在合法需要时才转向可变的。

回答by Kaleb Brasee

  1. Yes, thisdifferentiates between an instance variable and a method parameter variable of the same name.
  2. There's always debate on whether constructor or setter initialization is better. If you're only going to set the name and number when you first create the object, and won't need to update those variables later, just using the constructor and leaving out the setters is probably better. And yes, in the setter, you'd need to use thisif your parameter has the same name as the field you want to set.
  1. 是的,this区分同名的实例变量和方法参数变量。
  2. 关于构造函数或setter初始化哪个更好,总是存在争论。如果您只想在第一次创建对象时设置名称和编号,并且以后不需要更新这些变量,那么只使用构造函数并省略设置器可能会更好。是的,在 setter 中,this如果您的参数与要设置的字段同名,则需要使用。

回答by Justin Niessner

  1. Yes. Using the thiskeyword avoids issues.

  2. If there are logic in the get/set methods, then you should use them instead. Otherwise, setting the values in the constructor is valid.

  1. 是的。使用this关键字可以避免问题。

  2. 如果 get/set 方法中有逻辑,那么您应该改用它们。否则,在构造函数中设置的值是有效的。

回答by templatetypedef

There's no problem having the parameter using the same name as the field; the this.explicitly disambiguates and the program will behave as intended.

使用与字段相同的名称的参数没有问题;在this.明确歧义消除,并计划将表现为预期的。

Depending on your program it may or may not be advantageous to use setters instead of directly writing fields. If you write the values directly in the constructor, then you bypass any runtime checks that you might have in your setters, which could potentially cause your object to hold data it normally can't. On the other hand, if your setter tries to do something with the old value, then you probably don't want to call the setter because, in the constructor, there might not be a meaningful old value. I'd say it's not clearly better or worse to set the fields in the constructor than to use setters, so long as you're careful to avoid breaking the class invariants.

根据您的程序,使用 setter 代替直接写入字段可能有利也可能不利。如果您直接在构造函数中写入值,那么您将绕过您可能在 setter 中进行的任何运行时检查,这可能会导致您的对象保存通常无法保存的数据。另一方面,如果您的 setter 尝试使用旧值执行某些操作,那么您可能不想调用 setter,因为在构造函数中,可能没有有意义的旧值。我想说的是,在构造函数中设置字段并不比使用 setter 更好或更坏,只要您小心避免破坏类不变量。

回答by Alb

1) When the object scope property is the same as the argument name you must use thisto differentiate between them. When there is a name clash the local var or argument will take precedence over the property.

1) 当对象范围属性与参数名称相同时,您必须使用它this来区分它们。当出现名称冲突时,局部变量或参数将优先于属性。

For this reason, I don't like to ever have the exact same name for each as it can easily lead to bugs.

出于这个原因,我不喜欢为每个名称使用完全相同的名称,因为它很容易导致错误。

2) I also would use the setters from within the constructor, because if there ever needs to be a validation or some other operation done on the argument at time of setting you'll only have to make the change in one place. Otherwise it is duplication and violates the DRY (Don't Repeat Yourself)principle.

2) 我也会在构造函数中使用 setter,因为如果在设置时需要对参数进行验证或其他一些操作,您只需在一个地方进行更改。否则就是重复并违反DRY(不要重复自己)原则。

I would do:

我会做:

public myClass (string name, int number) {
    setName( name );
    setNumber( number );
}

回答by Mikel

Yes, this.avoids problems. Some people recommend that way, such as Rogue Wave in their book The Elements of Java Style.

是的,this.避免了问题。有些人推荐这种方式,例如 Rogue Wave 在他们的The Elements of Java Style一书中。

Other common ways of dealing with this are:

其他常见的处理方法是:

name members with a "m" or "m_" prefix

用“m”或“m_”前缀命名成员

private string m_name;
private int m_number;
public myClass(string name, int number) {
    m_name = name;
    m_number = number;
}

call the parameters a different name, usually a single letter or abbreviated version of the member name

将参数称为不同的名称,通常是成员名称的单个字母或缩写版本

private string name;
private int number;
public myClass(string nam, int num) {
    name = nam;
    number = num;
}

But I prefer the way you are using now with this.

但我更喜欢你现在使用的方式this