例如,我有一个方法可以显示有关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/

10-11 22:28
查看更多