6.4 内部类
来源:互联网 发布:qq主题下载软件 编辑:程序博客网 时间:2024/06/18 18:25
内部类是定义在其他类里面的类。
好处在于:
- 内部类可以直接使用外部类的方法和属性。
- 内部类对于同包内的其他类是不可见的。
- 匿名内部类可以简化回调函数的代码。其实这点用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 静态内部类
只是整合数据方便而已。
0 0
- 6.4 内部类
- 内部类
- 内部类
- 内部类
- 内部类
- 内部类
- 内部类
- 内部类
- 内部类
- 内部类
- 内部类
- 内部类
- 内部类
- 内部类
- 内部类
- 内部类
- 内部类
- 内部类
- 6.1 接口
- 6.2 接口的例子
- VS2013/MFC编程入门之十五(对话框:消息对话框)
- 6.3 Lambda表达式
- 继承与派生
- 6.4 内部类
- iOS开发- 常用的第三方资源
- 酷比魔方talk8x官方线刷教程疑问解析
- 深入探讨傅立叶变换、拉普拉斯变换、Z变换的联系与应用
- Struts2实现文件上传(相对路径)
- 74. Search a 2D Matrix&240. Search a 2D Matrix II
- 6.5 代理
- 前端开发常见的英语词汇整理
- 【Javascript基础】Boolean类型