在我的 Java 类中,我创建了一些属性和方法。然而,在其中一个方法中,我调用了类的属性,无论是否使用“this”,该方法都可以工作。在属性前面。如果这不是必要的,我想知道“这个”的目的是什么。
public String getName() {
return name;
}
^^ 有效 ^^
public String getName() {
return this.name;
}
^^ 有效 ^^
最佳答案
来自https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html :
"The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter."
“this”的使用不是强制性的。但引用对象的字段而不是方法或变量的参数是有用的。请参阅:
public class Person {
private String name = "John Smith";
public String getName() {
return name; // no need for keyword "this"
}
public String getFalseName() {
String name = "Bill Doe"; // this.name is shadowed
return name; // will return "Bill Doe" since keyword "this" is not used
}
public String getTrueName() {
String name = "Bill Doe"; // this.name is shadowed
return this.name; // Will return "John Smith";
}
public void setName( String name ){ // name is a parameter, this.name is shadowed now
this.name = name; // this.name is correctly assigned
}
}
关于java - 为什么我的 Java 类可以在不使用 "this."的情况下工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60068989/