6.4 内部类

内部类:定义在一个类中的类。
为什么要用内部类:
1)内部类可以访问其外围类的实例域,包括私有数据。
2)内部类可以对同包中的其他类隐藏。
3)定义一个回调函数,使用匿名内部类要便捷。

6.4.1 使用内部类访问对象的状态
实例:一个TimePrinter常规类,他需要通过TalkingClock类的共有方法访问beep标志。
注释:TimePrinter类被声明为私有的,这样只有TalkingClock的方法才能生成TimePrinter对象。内部类可以是私有类,常规类只能是包可见性或公有可见性。
例6-4源代码:
package com.corejava.innerclass;

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
/**
 * 
 * @author vincent
 * 
 */
public class InnerClassTest {

	public static void main(String[] args) {
		TalkingClock clock = new TalkingClock(1000, true);
		clock.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) {
			// TODO Auto-generated method stub
			Date now = new Date();
			System.out.println("At the tone, the time is " + now);
			if(beep)
				Toolkit.getDefaultToolkit().beep();
		}
		
	}
}

6.4.4局部内部类
使用背景:创建一个类的对象只需使用一次时,推荐使用局部内部类。例如上述代码中TimerPrinter这个类只在start方法中创建了对象并只使用了一次,这时可将TimerPrinter创建为局部内部类:
public void start() {
	class TimerPrinter 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 TimerPrinter();
	Timer t = new Timer(interval, listener);
	t.start();
}
注意:局部内部类不能用public或private声明,它的作用域被限定在声明这个局部类的块中;
局部类的好处是对外完全隐藏,即使TalkingClock类中的其他代码也不能访问它,除了start方法外,没有任何方法知道TimerPrinter类的存在。
局部类还有一个优点:除了能访问包含它的外部类,还能访问局部变量,不过这些局部变量必须被声明为final。

6.4.5由外部方法访问final变量
典型示例:将TalkingClock构造器的参数interval和beep移至start方法中。
public void start(int interval, final boolean beep) {
	class TimerPrinter 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 TimerPrinter();
	Timer t = new Timer(interval, listener);
	t.start();
}

6.4.6匿名内部类

1、将局部内部类深入,若只创建这个类的一个对象,就不用命名了。这种类就是匿名内部类。

小程序:

public void start(int interval, final boolean beep) {

ActiongListener listener = new ActionListener() {

public void actionPerformed(ActionEvent event) {

Date now = new Date();

System.out.println("At the tone, time is " + now);

if(beep)

Toolkit.getDefultToolkit().beep();

}

};

Timer t = new Timer(interval, listener);

t.start();

}

代码解析:创建了一个实现ActiongListener接口的类的新对象,这个新对象需要实现actionPerformed所定义的方法。

2、构造器的名字必须和类名相同,但是匿名类没有类名,所以匿名类没有构造器。取而代之的是将构造器的参数传递给超类(父类)构造器。尤其是内部类实现接口是不能有任何构造参数,而且还要提供一组括号,例如:

new InterfaceType() {

methods and data;

}

3、构造一个类的新对象共和构造一个匿名类的区别:

Person queen = new Person("Mary");//a Person object

Person count = new Person() {....}; //an object of an inner class extending Person

如果构造参数的闭源括号跟一个开花括号,表示正在定义的就是匿名内部类


例6-5源代码:将这个程序与之前的6-4相比较会发现匿名类的解决方案比较简单、实际和易于理解

package com.core.anonymousinnerclass;

import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.Timer;

/**
 * 
 * @author vincent
 *
 */
public class AnonymousInnerClass {

	public static void main(String[] args) {
		TalkingClock clock = new TalkingClock();
		clock.start(1000, true);
		
		//keep progra running until user selects "OK"
		JOptionPane.showMessageDialog(null, "Quit program?");
		System.exit(0);
	}
}

class TalkingClock {
	public void start(int interval, final boolean beep) {
		ActionListener listener = new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				Date now = new Date();
				System.out.println("At the tone, time is: " + now);
				if(beep)
					Toolkit.getDefaultToolkit().beep();
			}

		};
		Timer t = new Timer(interval, listener);
		t.start();
	}
}

6.4.7静态内部类
使用背景:只需要将一个类隐藏在另一个类的内部,并不需要内部类引用外围类对象时。
只有内部类可以声明为static,静态类除了不能生产外围类对象的引用外,与其他内部类一样。
例6-6
package com.core.staticinnerclass;

/**
 * 
 * @author vincent
 *
 */
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);	//不需要用new生成对象,静态方法可以直接引用
		
		System.out.println("min = " + p.getFirst());
		System.out.println("max = " + p.getSecond());
	}
			
}
	
	class ArrayAlg {

		//A pair of floating-point numbers
		public static class Pair {

			private double first;
			private double second;

			//Constructs a pair from two floating-point numbers
			public Pair(double f, double s) {
				first = f;
				second = s;
			}
			
			//Returns the first numbers of the pair
			public double getFirst() {
				return first;
			}
			
			//Return the second numbers of the pair
			public double getSecond() {
				return second;
			}
		}
		
		//minmax方法返回 Pair这个静态内部类
		public static Pair minmax(double[] values) {

			double min = Double.MAX_VALUE;
			double max = Double.MIN_VALUE;
			
			for (double v : values) {
				if (min > v)
					min = v;
				if (max < v)
					max = v;
			}
			return new Pair(min, max);
		}

	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值