Consider the following Java code fragment:
public class AThis fragment defines the class A which contains an static inner class B.
{
int y;
public static class B
{
int x;
void f () {}
}
}
A static inner class behaves like any ``outer'' class. It may contain methods and fields, and it may be instantiated like this:
A.B object = new A.B ();This statement creates an new instance of the inner class B. Given such an instance, we can invoke the f method in the usual way:
object.f();
Note, it is not necessarily the case that an instance of the outer class A exists even when we have created an instance of the inner class. Similarly, instantiating the outer class A does not create any instances of the inner class B.
The methods of a static inner class may access all the members (fields or methods) of the inner class but they can access only static members (fields or methods) of the outer class. Thus, f can access the field x, but it cannot access the field y.
本文详细解析了Java中静态内部类的行为特征及其实例化过程。静态内部类类似于外部类,可以独立实例化而不依赖于外部类的存在。文章还介绍了如何创建静态内部类的实例,并调用其方法。
8313

被折叠的 条评论
为什么被折叠?



