Java this:不能在静态上下文中使用 this

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16315488/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:17:01  来源:igfitidea点击:

this: Cannot use this in static context

javathis

提问by Cyborgz

Can you please help me with below code. The error is: "Cannot use This in a static context"

你能帮我看看下面的代码吗?错误是:“不能在静态上下文中使用它”

public class Sample2 {
    /**
     * @param args
     */
    public static void main(String[] args) 
    {
        Sample2 sam=new Sample2();  

        //Below code works fine
        System.out.println(sam);

        //Below code is displaying error
        System.out.println(this);
    }
}

采纳答案by Priyanka Vishwakarma

See, "this" keyword refers to current object due to which method is under exceution. As, you cannot call static method using instance of class. That is why, "this" can't be used in the above example in a static method as it is trying to print current instance wich is not at all created. So, I think thats why there is an compile time error that you are getting.

请参阅,“this”关键字指的是当前对象,因为哪个方法正在执行。因为,您不能使用类的实例调用静态方法。这就是为什么在上面的示例中不能在静态方法中使用“this”,因为它试图打印根本没有创建的当前实例。所以,我认为这就是您收到编译时错误的原因。

回答by Suresh Atta

In java you can not use this in static methods (static context).

在 Java 中,您不能在静态方法(静态上下文)中使用 this。

Staticmethods do not point to any instance of the enclosing class.

Static方法不指向封闭类的任何实例。

A static method cannot refer to “this” or “super” keywords in anyway

静态方法无论如何都不能引用“this”或“super”关键字

Refer official docson thiskeyword

请参阅有关关键字的官方文档

回答by Matten

They keyword thisrefers to the instanceof the class. In a static context, you have no instance, therefore you can't refer it.

它们的关键字this是指类的实例。在静态上下文中,您没有实例,因此无法引用它。

For more information, refer to this answer: What is the meaning of "this" in Java?

有关更多信息,请参阅此答案:Java 中“this”的含义是什么?

回答by Vivek Vermani

If we try to access this from a static context , compiler has no way to guess which instance, you are referring too. main is a static method here.

如果我们尝试从静态上下文访问它,编译器将无法猜测您所指的是哪个实例。main 是这里的静态方法。

回答by Jain

writing this means in static context we are expecting to return the address of the object. Though its totally legal to have an object calling static methods but it is not an obligation. So compiler stops possibility of any error in case object is not created for the class.

写这意味着在静态上下文中我们期望返回对象的地址。虽然让对象调用静态方法是完全合法的,但这不是义务。因此,如果没有为该类创建对象,编译器会停止出现任何错误的可能性。