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
當描述事物時,事物的內部還有事物,該事物用內部類來描述。
因爲內部事物在使用外部事物的內容。