静态方法或块属于该类,它们将与该类一起加载到内存中。您可以调用静态方法而无需创建对象。(使用类名作为参考)。
而Java中的 “ this”充当对当前对象的引用。但是静态上下文(方法和块)没有任何实例,它们属于该类。
从简单的意义上说,要使用“ this ”,该方法应由一个对象调用,而静态方法并不总是必需的。
因此,不能通过静态方法使用此关键字。
在下面的Java程序中,类ThisExample 包含一个带有setter和getter方法以及实例方法display()的私有变量名称。从main方法(静态方法)中,我们尝试使用“ 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