简体   繁体   English

Java“this”在构造函数中

[英]Java “this” in constructors

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."? 是否更好地使用set方法,如果是这样,我应该使用“this”。

Thank you very much 非常感谢你

  1. Yes, it avoids the name clash. 是的,它避免了名称冲突。 In the constructor's context, the name name refers to the parameter, and the name this.name refers to the instance field. 在构造函数的上下文中, name引用参数,名称this.name引用实例字段。
  2. Depends on what you mean by "better." 取决于“更好”的意思。 Personally, I would make the name and number fields final, so the class is immutable. 就个人而言,我会将namenumber字段设为final,因此该类是不可变的。 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. Yes, this differentiates between an instance variable and a method parameter variable of the same name. 是的, this区分实例变量和同名的方法参数变量。
  2. There's always debate on whether constructor or setter initialization is better. 关于构造函数或setter初始化是否更好的问题一直存在争论。 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. 如果您只是在第一次创建对象时设置名称和编号,并且以后不需要更新这些变量,那么仅使用构造函数并省略setter可能会更好。 And yes, in the setter, you'd need to use this if your parameter has the same name as the field you want to set. 是的,在setter中,如果您的参数与您要设置的字段具有相同的名称,则需要使用this选项。

There's no problem having the parameter using the same name as the field; 参数使用与字段相同的名称没有问题; the this. this. explicitly disambiguates and the program will behave as intended. 明确消除歧义,程序将按预期运行。

Depending on your program it may or may not be advantageous to use setters instead of directly writing fields. 根据您的程序,使用setter而不是直接写字段可能有利也可能没有用。 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. 如果直接在构造函数中编写值,则可以绕过setter中可能存在的任何运行时检查,这可能会导致对象保留通常无法保存的数据。 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. 另一方面,如果你的setter试图用旧值做某事,那么你可能不想调用setter,因为在构造函数中,可能没有有意义的旧值。 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更明显更好或更糟,只要你小心避免破坏类不变量。

  1. Yes. 是。 Using the this keyword avoids issues. 使用this关键字可避免出现问题。

  2. If there are logic in the get/set methods, then you should use them instead. 如果get / set方法中有逻辑,那么您应该使用它们。 Otherwise, setting the values in the constructor is valid. 否则,在构造函数中设置值是有效的。

1) When the object scope property is the same as the argument name you must use this to differentiate between them. 1)当对象范围属性与参数名称相同时,必须使用this来区分它们。 When there is a name clash the local var or argument will take precedence over the property. 当存在名称冲突时,本地var或参数将优先于该属性。

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. 2)我也会在构造函数中使用setter,因为如果在设置时需要对参数进行验证或其他操作,则只需要在一个地方进行更改。 Otherwise it is duplication and violates the DRY (Don't Repeat Yourself) principle. 否则它是重复并违反DRY(不要重复自己)原则。

I would do: 我会做:

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

Yes, this. 是的, this. avoids problems. 避免问题。 Some people recommend that way, such as Rogue Wave in their book The Elements of Java Style . 有些人推荐这种方式,比如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

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

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