这是基础班的一个练习题:老师说B选项错误的原因是主函数是静态的,不能在里面new对象。不能理解。
class Demo
{
public void func()
{
//位置1;
new Inner();
}
class Inner{}
public static void main(String[] args)
{
Demo d=new Demo();
// 位置2
new Inner();//不可以,因为主函数是静态的。如果访问inner需要被static修饰。
}
}
A.在位置1写 new Inner();//ok
B.在位置2写 new Inner();
C.在位置2写 new d.Inner();//错误,格式错误。 new new Demo().Inner();
D.在位置2写 new Demo.Inner();//错误,因为inner不是静态的。
通常写程序不是经常在主函数里new对象吗?这里的B选项为什么就不行呢?谢谢了
|
|