你能帮我写下下面的代码吗?错误是:“不能在静态上下文中使用这个”
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”关键字是指当前对象,因为哪个方法正在执行中。因为,您不能使用类的实例调用静态方法。这就是为什么在上面的示例中不能在静态方法中使用“this”,因为它试图打印根本没有创建的当前实例。所以,我认为这就是为什么会出现编译时错误。
关于java - this:不能在静态上下文中使用 this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16315488/