简体   繁体   English

没有传递任何参数时,我应该在构造函数中使用关键字“ this”吗?

[英]Should I be using keyword “this” in a constructor when no arguments are being passed?

I was wondering whether I should be using "this" in Java when no arguments are being passed in the constructor of a class. 我想知道当在类的构造函数中未传递任何参数时,是否应该在Java中使用“ this”。

private int id;

public ClassName() {
    this.id = -1;
}

OR 要么

 private int id;

public ClassName() {
    id = -1;
}

Thank you for your time. 感谢您的时间。

If there is no argument, then it's all the same. 如果没有参数,那么都是一样的。 However it's always a good practice. 但是,这始终是一个好习惯。

No, this in this case is optional. 不,在这种情况下, this是可选的。 Only need it when the constructor is passed a parameter named id to avoid variable shadowing. 仅在将构造函数传递给名为id的参数时需要它,以避免变量阴影。

You shouldn't be doing either actually. 您实际上不应该这样做。 You should initize that variable in the declaration. 您应该在声明中初始化该变量。

If you have a more complex case, the principle of least redundancy applies: don't write it where it isn't required. 如果情况比较复杂,则应采用最少冗余的原则:不要在不需要的地方写它。

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

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