Java支持哪些嵌套類?
Java將嵌套類分成兩個主要的分類
嵌套頂級類
當你在其它類的外面聲明一個類時
class TopLevelClass
{
static class NestedTopLevelClass
{
}
}
就象靜態的字段和靜態的方法一樣(也可稱為類字段和類方法)
class TopLevelClass
{
static int staticField;
int instanceField;
static class NestedTopLevelClass
{
static
{
System
// System
}
{
System
// System
}
}
}
在上面NestedTopLevelClass類的類初始化和對象初始化代碼塊中
警告
雖然NestedTopLevelClass不能訪問TopLevelClass的實例字段
Listing
// NestedTopLevelClassDemo
class TopLevelClass
{
static class NestedTopLevelClass
{
int myInstanceField;
NestedTopLevelClass (int i)
{
myInstanceField = i;
}
}
}
class NestedTopLevelClassDemo
{
public static void main (String [] args)
{
TopLevelClass
ntlc = new TopLevelClass
System
}
}
在運行後
NestedTopLevelClassDemo的main()方法創建了一個NestedTopLevelClass變量
這時
Listing
// NestingAndShadowingDemo
class TopLevelClass
{
private static int a =
private static int b =
static class NestedTopLevelClass
{
private static int a =
static class NestedNestedTopLevelClass
{
void printFields ()
{
System
System
}
}
}
}
class NestingAndShadowingDemo
{
public static void main (String [] args)
{
TopLevelClass
nntlc = new TopLevelClass
NestedNestedTopLevelClass ();
nntlc
}
}
在運行時
a =
b =
NestingAndShadowingDemo可以編譯運行證明你可以在頂級嵌套類中嵌套頂級嵌套類
使用嵌套頂級類
提示
實例內部類(Instance inner classes)
假設你在聲明嵌套類時
提示
本地內部類(Local inner classes)
除了以上的類嵌套外
相對於實例內部類來說
Listing
// LocalInnerClassDemo
import java
class ComputerLanguage
{
private String name;
ComputerLanguage (String name)
{
this
}
public String toString ()
{
return name;
}
}
class LocalInnerClassDemo
{
public static void main (String [] args)
{
ComputerLanguage [] cl =
{
new ComputerLanguage (
new ComputerLanguage (
new ComputerLanguage (
new ComputerLanguage (
new ComputerLanguage (
new ComputerLanguage (
new ComputerLanguage (
new ComputerLanguage (
new ComputerLanguage (
new ComputerLanguage (
new ComputerLanguage (
new ComputerLanguage (
new ComputerLanguage (
new ComputerLanguage (
new ComputerLanguage (
new ComputerLanguage (
new ComputerLanguage (
new ComputerLanguage (
new ComputerLanguage (
new ComputerLanguage (
new ComputerLanguage (
new ComputerLanguage (
new ComputerLanguage (
};
Enumeration e = enumerator ((Object []) cl);
while (e
System
}
static Enumeration enumerator (final Object [] array)
{
class LocalInnerClass implements Enumeration
{
private int index =
public boolean hasMoreElements ()
{
return index < array.length;
}
public Object nextElement ()
{
return array [index++].toString ();
}
}
return new LocalInnerClass ();
}
}
在運行後, LocalInnerClassDemo產生以下的輸出:
Ada
Algol
APL
Assembly - IBM 360
Assembly - Intel
Assembly - Mostek
Assembly - Motorola
Assembly - VAX
Assembly - Zilog
BASIC
C
C++
Cobol
Forth
Fortran
Java
LISP
Logo
Modula 2
Pascal
Perl
Prolog
Snobol
LocalInnerClassDemo展示了在LocalInnerClassDemo的enumerator()類方法中聲
From:http://tw.wingwit.com/Article/program/Java/hx/201311/26930.html