论坛首页 Java企业应用论坛

Think in Java 中一道有意思的题目

浏览 2721 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2007-02-07  
第3版中 第8章的一道题目 关于内部类的

题目如下:
创建一个接口U,它包含三个方法.创建第一个类A,它包含一个方法,在此方法中通过创建一个匿名内部类,来生成指向U的引用.创建第二个类B,它包含一个由U构造成的数组.B应该有几个方法,第一个方法可以接受对U的引用并存储到数组中;第二个方法将数组中的引用设为null;第三个方法遍历此数组,并在U中调用这些方法.在main()中,创建一组A的对象和一个B的对象.用那些A类对象所产生的U类型的引用填充B对象的数组.使用B回调所有的A的对象.再从B中一处某些U的引用.

以下是我的代码  这个题目说明了内部类的一些特性
package Unit8;
interface U{ 	//定义一个接口
	void a();
	void b();
	void c();
}
class A{
	private int a = 0;		//类A的私有成员 注意这个
	private String name;
	public A(String name){
		this.name = name;
	}
	public U f1(){			//返回接口U的引用
		return new U(){
			public void a(){System.out.println(name+':'+a);}
			public void b(){a++;}
			public void c(){}
		};
	}
}

class B{
	public U[] arr = new U[10];
	private int index = 0;
	public void add(U u){
		if(index <arr.length){
			arr[index] = u;
			index++;
		}
		else
			System.out.print("The array has full");
	}
	
	public void clear(int index){
		arr[index] = null;
	}
	public void go(){
		for(int i=0;i<arr.length;i++){
			arr[i].a();
			arr[i].b();
			arr[i].c();
		}
	}
}
public class Ex_28 {
	public static void main(String[] args){
		A a1 = new A("a1");			//创建三个A的实例
		A a2 = new A("a2");
		A a3 = new A("a3");
		B b = new B();
		for(int i=0;i<5;i++){		//A的每个实例分别返回U的引用放到B的数组里
			b.add(a1.f1());	
		}
		for(int i=0;i<3;i++){
			b.add(a2.f1());	
		}
		for(int i=0;i<2;i++){
			b.add(a3.f1());	
		}
		b.go();	//用B回调A 从输出结果上看 几个U的引用在操作各自的对象
	}
}

//匿名内部类 可以引用它的外部类

输出
引用

a1:0
a1:1
a1:2
a1:3
a1:4
a2:0
a2:1
a2:2
a3:0
a3:1
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics