this: Cannot use this in static context

早过忘川 提交于 2019-11-26 08:27:24

问题


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);
    }
}

回答1:


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.




回答2:


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

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




回答3:


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

Static methods do not point to any instance of the enclosing class.

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

Refer official docs on this keyword




回答4:


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.




回答5:


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.



来源:https://stackoverflow.com/questions/16315488/this-cannot-use-this-in-static-context

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!