为什么静态方法中不允许"this"?

ami*_*ngh -2 java static

我知道this代表调用方法的对象和static方法没有绑定到任何对象,但我的问题仍然是你可以在类对象上调用静态方法.

为什么java使这个东西可用而不是this

duf*_*ymo 9

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)

  • @amicngh静态方法在类的所有实例之间共享,因此任何实例都可以调用静态方法.虽然`this`指向当前实例,当你从静态方法中调用`this`时,Java如何确定`this`指向哪个实例?请记住,也可以从另一个类的实例调用静态方法. (2认同)