Java – this: cannot be used in a static context

Can you help me with the following code? The error is: "cannot be used in 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);
    }
}

Solution

See "this" keyword refers to the current object, because which method is in an abnormal state Because you can't call static methods using instances of classes This is why in the above example, "this" cannot be used for static methods because it attempts to print the current instance and is not created at all So I think that's why you have a compile - time error

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>