内部类是定义在其他类里面的类。
好处在于:
- 内部类可以直接使用外部类的方法和属性。
- 内部类对于同包内的其他类是不可见的。
- 匿名内部类可以简化回调函数的代码。其实这点用Lambda更简洁。
1 使用内部类获取对象的状态
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
/**
* This program demonstrates the use of inner classes.
* @version 1.11 2015-05-12
* @author Cay Horstmann
*/
public class InnerClassTest
{
public static void main(String[] args)
{
TalkingClock clock = new TalkingClock(1000, true);
clock.start();
// keep program running until user selects "Ok"
JOptionPane.showMessageDialog(null, "Quit program?");
System.exit(0);
}
}
/**
* A clock that prints the time in regular intervals.
*/
class TalkingClock
{
private int interval;
private boolean beep;
/**
* Constructs a talking clock
* @param interval the interval between messages (in milliseconds)
* @param beep true if the clock should beep
*/
public TalkingClock(int interval, boolean beep)
{
this.interval = interval;
this.beep = beep;
}
/**
* Starts the clock.
*/
public void start()
{
ActionListener listener = new TimePrinter();
Timer t = new Timer(interval, listener);
t.start();
}
public class TimePrinter implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
System.out.println("At the tone, the time is " + new Date());
if (beep) Toolkit.getDefaultToolkit().beep();
}
}
}
2 内部类的语法规则
使用OuterClass.this
public void actionPerformed(ActionEvent event)
{
...
if (TalkingClock.this.beep) Toolkit.getDefaultToolkit().beep();
}
使用outerObject.new InnerClass(construction parameters)
ActionListener listener = this.new TimePrinter();
3 内部类有没有用?必要吗?是不是安全的?
内部类只是编译器施加的语法技巧而已,实际上仍然是一个类。
4 局部内部类
public void start()
{
class TimePrinter implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
System.out.println("At the tone, the time is " + new Date());
if (beep) Toolkit.getDefaultToolkit().beep();
}
}
ActionListener listener = new TimePrinter();
Timer t = new Timer(interval, listener);
t.start();
}
5 方法访问外部变量
这个变量必须设定成为final才可以。
如果想要动态改变,那就不要死板,比如说声明一个长度为1的数组,其内数字不就是可以改变的嘛。
6 匿名内部类
public void start(int interval, boolean beep)
{
ActionListener listener = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
System.out.println("At the tone, the time is " + new Date());
if (beep) Toolkit.getDefaultToolkit().beep();
}
};
Timer t = new Timer(interval, listener);
t.start();
}
7 静态内部类
只是整合数据方便而已。