为什么不能在这里使用 'this' 关键字?

why can't the 'this' keyword be used here?

我了解到this指的是当前对象。所以为什么我不能使用 objectname.fun(objectname.nonstaticmember) 而不是 objectname.fun(this.nonstaticmember)

请参考下面的示例,并在最后看到最后两个评论。

public class Question
{
    int data;

    void myfun(int data)
    {
        System.out.println("data=="+data);
    }

    public Question(int data)
    {
        this.data = data;
        // TODO Auto-generated constructor stub
    }

    public static void main(String[] args)
    {   
        Question question = new Question(10);
        //question.myfun(question.data);//WORKS
        question.myfun(this.data);//DOES NOT WORK
    }
}

main() 是一个 static 方法(class 方法)它不 运行 来自一个对象。由于它在 class 上下文中,关键字 this 没有任何意义(它没有可引用的对象)。

正如您提到的,this 关键字用于引用当前对象而不是 class 本身。在您的情况下,您正试图在静态方法 main 中使用它 (this)。还要检查这个 link.

在java中这个关键字用来引用当前对象但是main是一个静态方法,在静态方法里面这个关键字没有意义。

public class Line {
public static void main(String[] args){
    System.out.println(this);

} }

输出:编译时错误"non-static variable this cannot be referenced from a static context"。