我知道this代表调用方法的对象和static方法没有绑定到任何对象,但我的问题仍然是你可以在类对象上调用静态方法.
为什么java使这个东西可用而不是this?
this 指向该类的当前实例.
静态方法与类相关联,而不是与实例相关联,因此没有任何内容可供this指向.
这是一个例子:
public class Foo {
private String name;
public static void someClassMethod() { System.out.println("associated with a class"); }
public Foo(String n) { this.name = n; }
public String getName() { return this.name; }
public void setName(String n) { this.name = n; }
public void doAnotherThing() {
Foo.someClassMethod(); // This is what is really happening when you call a static method in an non-static method.
}
}
Run Code Online (Sandbox Code Playgroud)