static inner class

来源:互联网 发布:淘宝购物少件拒收 编辑:程序博客网 时间:2024/06/09 20:56

Consider the following Java code fragment:

public class A
{
int y;

public static class B
{
int x;

void f () {}
}
}
This fragment defines the class A which contains an static inner class B.

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.

原创粉丝点击