例如,我有一个方法显示有关 Employee 实例的信息
//Displaying the instance of the object information in a anesthetically pleasing manner
public void display() {
System.out.println("Employee Information");
seperationLine();
System.out.println("Name: " + getName());
seperationLine();
System.out.println("PPS number: " + getPpsNum());
seperationLine();
System.out.println("Salary: " + getSalary());
}
在方法和其他需要使用属性的方法中我应该使用this
关键字还是没有必要
//Displaying the instance of the object information in a anesthetically pleasing manner
public void display() {
System.out.println("Employee Information");
seperationLine();
System.out.println("Name: " + this.getName());
seperationLine();
System.out.println("PPS number: " + this.getPpsNum());
seperationLine();
System.out.println("Salary: " + this.getSalary());
}
最佳答案
这实际上更像是一个风格问题。
在早期,编辑者不够聪明,无法理解:这些是类的字段,因此它们可以/应该以不同的颜色突出显示(与局部变量相比)。
但是现在连小编辑都明白这样的事情了。因此,在不需要使用 this
的地方使用它并不会带来太多好处。所以,我建议:仅在 have to 时写下this
.
除此之外,真正的问题是:不要编写这样的 display()
方法。现实世界的实践:@Override toString() 方法,并让它返回类的有意义表示。
然后,每当您打算记录或显示类的实例时,您都可以调用 employee.toString()
...并按照您喜欢的方式使用返回的字符串。
含义:向控制台显示是一个非常糟糕的主意。例如,如果您想稍后将内容记录到文件中怎么办?!
关于java - 在类方法中包含 this 关键字是个好习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58438594/