这个:不能在静态上下文中使用它 [英] this: Cannot use this in static context

查看:159
本文介绍了这个:不能在静态上下文中使用它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮我解决下面的代码。错误是:无法在静态上下文中使用此内容

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


推荐答案

参见,this关键字指的是当前对象,因为哪种方法处于优先级。因为,您不能使用类的实例调用静态方法。这就是为什么这个不能在上面的例子中用于静态方法,因为它试图打印当前没有创建的实例。所以,我认为这就是为什么你会得到一个编译时错误。

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.

这篇关于这个:不能在静态上下文中使用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆