內部類是定義在一個類內部的類。
內部類方法可以訪問該類定義所在的作用域的數據,包括私有數據。
內部類對同一包中的其他類不可見。
使用內部類定義回調函數可以避免寫大量代碼。
class TalkingClock
{
public TalkingClock(int interval, boolean beep) { . . . }
public void start() { . . . }
private int interval;
private boolean beep;
private class TimePrinter implements ActionListener
// an inner class
{
Date now = new Date();
System.out.println("At the tone, the time is " + now);
if (beep) Toolkit.getDefaultToolkit().beep();
}
}
內部類既可以訪問自身的數據域,也可以訪問創建它的外圍類對象的數據域。內部類有一個隱式引用,其指向外圍類對象。
public void actionPerformed(ActionEvent event)
{
Date now = new Date();
System.out.println("At the tone, the time is " + now);
if (outer.beep) Toolkit.getDefaultToolkit().beep();
}
內部類的默認構造函數
public TimePrinter(TalkingClock clock) // automatically generated code
{
outer = clock;
}
局部內部類,不能用private和public聲明,start方法都不能訪問它。
public void start()
{
class TimePrinter implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
Date now = new Date();
System.out.println("At the tone, the time is " + now);
if (beep) Toolkit.getDefaultToolkit().beep();
}
}
ActionListener listener = new TimePrinter();
Timer t = new Timer(1000, listener);
t.start();
}
匿名內部類
public void start(int interval, final boolean beep)
{
ActionListener listener = new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
Date now = new Date();
System.out.println("At the tone, the time is " + now);
if (beep) Toolkit.getDefaultToolkit().beep();
}
};
Timer t = new Timer(1000, listener);
t.start();
}
匿名構造了不能有構造函數,而是把構造函數參數傳遞給超類構造函數,
new SuperType(construction parameters)
{
inner class methods and data
}
內部類實現接口時,不能有任何參數
new InterfaceType() { methods and data }
靜態內部類
class ArrayAlg
{
public static class Pair
{
. . .
}
. . .
}
靜態內部類對象除了沒有對生產它的外部類對象的引用特權外,與其他的內部類完全一樣。