在 Java 的静态上下文中可以使用 this 关键字吗?

java 8object oriented programmingprogramming更新于 2025/9/1 19:56:17

静态方法或静态块属于类,它们会随类一起加载到内存中。无需创建对象即可调用静态方法(使用类名作为引用)。

而 Java 中的"this" 则充当当前对象的引用。但是静态上下文(方法和块)没有任何实例,它们属于类。

简单来说,要使用"this",方法应该由对象调用,而静态方法并不总是需要这样做。

因此,不能在静态方法中使用 this 关键字。

示例

在下面的 Java 程序中,类 ThisExample 包含一个私有变量 name,该变量具有 setter 和 getter 方法,以及一个实例方法 display()。我们尝试在主方法(静态)中使用"this"调用 display() 方法。

public class ThisExample {
   private String name;
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public void display() {
      System.out.println("name: "+this.getName());
   }
   public static void main(String args[]) {
      this.display();
   }
}

编译时,该程序会报错,如下所示 −

编译时错误

ThisExample.java:17: error: non-static variable this cannot be referenced from a static context
      this.display();
      ^
1 error

相关文章