Public class ThisTest{
public void doSomething(){
System.out.println("This is a test!");
}
public static void main(String[] agrs){
ThisTest th = new ThisTest();
th.doSomething();
//以下为测试语句
System.out.println(this);
}
}
报错信息:
得出结论:
因为main方法是静态方法属于类,无法直接使用对象级别的变量和方法,也就是实例属性和实例方法。而关键字“ this”用作对实例的引用,因此不能在静态方法中使用“ this”引用。
原因(个人理解,勿喷):静态方法在类加载时就会被加载到方法区中,而此时,main函数还没有执行,没有new出对象th,所以无法使用对象级别的属性和方法。
补充:System.out.println(this); //会默认调用对象中的toString()