SCJP题,关于inner

ttt 2002-01-30 08:50:23
Why won't the following class compile?

class A {
private int x;
public static void main(String[] args) {
new B();
}
class B {
B() {
System.out.println(x);
}
}
}

A. Class B tries to access a private variable defined in its ouer class.
B. Class A attempts to create an instance of B when there is no current instance of class A.
C. Class B's constructor must be public.
答案是B, 为什么???
...全文
98 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
ajiao 2002-01-30
  • 打赏
  • 举报
回复
thinking in java 中关于 "the static keyword"是这样描述的
since static methods don’t need any objects to be created before they are used, they cannot directly access non-static members or methods by simply calling those other members without referring to a named object (since non-static members and methods must be tied to a particular object).
1.static method 它的运作不依赖于所属的class object上,而non-static data/method
必须知道他隶属于哪一个object他才可以运作,所以static method不可以直接存取non-static members or methods。是不可以直接存取,而不是不可以存取non-static members or methods,如果指明她所属的object的话。
2.如果在一个non-static方法中用new B();是不会出错的
还是会出错的,道理一样,inner classes B()的执行需要一个object
3.agree karma
ajiao 2002-01-30
  • 打赏
  • 举报
回复
new b() is a OBJECT not a reference
lanmarco 2002-01-30
  • 打赏
  • 举报
回复
一个不太准确的理解但是通常有用:
把inner class当作outer class的一个method来理解,就方便多了:)
lanmarco 2002-01-30
  • 打赏
  • 举报
回复
一个不太准确的理解但是通常有用:
把inner class当作outer class的一个method来理解,就方便多了:)
Patrick_DK 2002-01-30
  • 打赏
  • 举报
回复
因为在static方法中只能处理static变量

而你的内部类是non-static的,所以出错

如果在一个non-static方法中用new B();是不会出错的
karma 2002-01-30
  • 打赏
  • 举报
回复
by definition, inner classes are not static, you have to do
A a = new A();
B b = a.new B();
hht 2002-01-30
  • 打赏
  • 举报
回复
内部类是依附于外部类存在的,没有外部类实例,内部类实例当然不可能存在,和成员变量的感觉差不多,除非声明成static,静态内部类也是top level class的一种。

23,407

社区成员

发帖
与我相关
我的任务
社区描述
Java 非技术区
社区管理员
  • 非技术区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧