定义在其他类中的类就是内部类,内部类的外面一层就是外部类。简单来说,内部类和调用这个类的方法处于同一个类中,外部类就是和调用这个类的方法不在同一个类中。
拿上一节关于事件监听的程序举例:
内部类:
class frame1 extends JFrame {
private JButton btdialog;
public frame1(){
setTitle("事件监听器");
setBounds(100,100,500,400);
btdialog = new JButton("窗口");
//添加事件监听器对象 这里的DialogEventListener就是内部类
btdialog.addActionListener(new DialogEventListener());
//将按钮添加到JFrame中,此时是默认布局格式
add(btdialog);
//JFrame必备的两条语句,显示和自动退出
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//内部类 DialogEventListener,实现ActionListener接口,这里DialogEventListener没有出jframe1这个类的范围
class DialogEventListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e){
JDialog dialog = new JDialog();
dialog.setBounds(300,200,400,400);
dialog.setVisible(true);
}
}
外部类:
class frame1 extends JFrame {
private JButton btdialog;
public frame1(){
setTitle("事件监听器");
setBounds(100,100,500,400);
btdialog = new JButton("窗口");
//添加事件监听器对象(面向对象思想),和内部类 类似,不过DialogEventListener在frame1的类声明范围外
btdialog.addActionListener(new DialogEventListener());
//将按钮添加到JFrame中,此时是默认布局格式
add(btdialog);
//JFrame必备的两条语句,显示和自动退出
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
//外部类 DialogEventListener,已经出了jframe1的类声明范围,实现ActionListener接口
class DialogEventListener implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e){
JDialog dialog = new JDialog();
dialog.setBounds(300,200,400,400);
dialog.setVisible(true);
}
}
以上