java - 为什么我的 Java 类可以在不使用 "this."的情况下工作?

标签 java

在我的 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/

相关文章:

java - 从字符串到字节数组,然后再到字符串

java - Restful Web 服务 Struts 2

java - 使用java从一个oracle数据库中选择并批量插入到另一个oracle数据库中

java - 如何打印不重复的字符串?

java - Eclipse 插件 : Enablement of an Action based on the current selection

java - 如何在动画之前和之后执行 Action

java - 匹配连续的单个字符作为整个单词

java - Hibernate 中 n 个表到 1 个类的运行时单向映射

java - WAKEUP 在 notify/notifyall 上下文中真正意味着什么?

java - LinkedHashSet 在低级数据存储获取 Java 中作为 HashSet 返回