内部类
定义在一个类中的类。
书中提到的,为什么使用内部类?
- 内部类方法可以访问该类定义所在的作用域中的数据, 包括私有的数据。
- 内部类可以对同一个包中的其他类隐藏起来。
- 当想要定义一个回调函数且不想编写大量代码时,使用匿名 (anonymous) 内部类比较便捷。
1.使用内部类访问对象状态
书中的例子:
构造一个语音时钟时需要提供两个参数:发布通告的间隔和开关铃声的标志。
package com.zyx.test;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
public class InnerClass_2 {
public static void main(String[] args) {
TalkingClock talkingClock = new TalkingClock(1000,true);
talkingClock.start();
JOptionPane.showMessageDialog(null,"Quit program?");
System.exit(0);
}
class TalkingClock{
private int interval;
private boolean beep;
public TalkingClock(int interval,boolean beep){
this.interval = interval;
this.beep = beep;
}
public void start(){
ActionListener listener = new TimePrinter();
Timer t = new Timer(interval,listener);
t.start();
}
public class TimePrinter implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("At the tone , the time is"+new Date());
if(beep){
Toolkit.getDefaultToolkit().beep();
}
}
}
}
}
2.局部内部类
public void start(){
class TimePrinter implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
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();
}
局部内部类,不能用public ,private 访问说明符修饰。它的作用域呗限定在声明这个局部类的块中。
局部类有一个优势, 即对外部世界可以完全地隐藏起来。即使 TalkingClock 类中的其他
代码也不能访问它。除 start 方法之外, 没有任何方法知道 TimePrinter 类的存在。
3.匿名内部类
public void start(int interval,boolean beep){
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("At the tone , the time is"+new Date());
if(beep){
Toolkit.getDefaultToolkit().beep();
}
}
};
Timer t = new Timer(interval,listener);
t.start();
}
匿名内部类的语法:
new SuperType(construction parameters)
{
inner class methods and data
}
4.静态内部类
书中的例子:
package com.zyx.test;
import java.util.logging.Logger;
/*
* 静态内部类
* */
public class StaticInnerClass {
public static void main(String[] args) {
double[] d = new double[20];
for (int i = 0; i < d.length; i++) {
d[i] = 100 * Math.random();
ArrayAlg.Pair p = ArrayAlg.minmax(d);
System.out.println(p.getFirst());
System.out.println(p.getSecond());
}
}
}
class ArrayAlg{
public static class Pair{
private double first;
private double second;
public Pair(double f,double s){
first = f;
second = s;
}
public double getFirst(){
return first;
}
public double getSecond(){
return second;
}
}
public static Pair minmax(double[] values){
double min = Double.POSITIVE_INFINITY;
double max = Double.NEGATIVE_INFINITY;
Logger.getGlobal().info();
for(double v : values){
if(min > v){
min = v;
}
if(max < v){
max = v;
}
}
return new Pair(min,max);
}
}