static:内部类就具备static的特性。
当内部类被static修饰后,只能直接访问外部类中的static成员。出现了访问局限。
在外部其他类中,如何直接访问static内部类的非静态成员呢?
new Outer.Inner().function();
在外部其他类中,如何直接访问static内部类的静态成员呢?
outer.Inner.function();
注意:当内部类中定义了静态成员,该内部类必须是static的。
当外部类中的静态方法访问内部类时,内部类也必须是static的。
class Outer
{
private static int x = 3;
static class Inner//静态内部类
{
static void function()
{
System.out.println("innner :"+x);
}
}
static class Inner2
{
void show()
{
System.out.println("inner2 show");
}
}
public static void method()
{
//Inner.function();
new Inner2().show();
}
}
class InnerClassDemo2
{
public static void main(String[] args)
{
Outer.method();
//Outer.Inner.function();
//new Outer.Inner().function();
//直接访问内部类中的成员。
// Outer.Inner in = new Outer().new Inner();
// in.function();
}
}
二、内部类定义原则
内部类通常只定义在成员位置处,权限定义为private,static
当描述事物时,事物的内部还有事物,该事物用内部类来描述。
因为内部事物在使用外部事物的内容。