包装类:
当为了增强某类A的功能时,可以设计一个包装类B,该包装类B实现对类A的增强。在I/O流中,有比较多的包装类。如:FileInputStream 是对File类的增强,FileOutputStream是对File类的增强。
FileInputStream fin = new FileInputStream(new File("a"));
FileOutputStream fout = new FileOutputStream(new File("b"));
定义一个包装类有5个步骤:
1、编写一个类B,改类用来增强类A
2、在类B中定义个类A的成员变量clazz_a
3、类B定义一个构造函数,接受一个类A的参数
4、对类A的某个方法可以进行覆写或增强,或定义一些新的方法
5、对类A中不需进行增强的方法,则直接调用类A的方法。
//下面是一个例子,
//class A, 定义了a,b,c三个方法
public class A {
public void method_a(){
System.out.println("this is method a");
}
public void method_b(){
System.out.println("this is method b");
}
public void method_c(){
System.out.println("this is method c");
}
}
//class B,对A进行增强
public class B {
//1.定义一个类A的成员变量
private A a = null;
//该成员变量以参数形式传给B的构造函数
public B(A a){
this.a = a;
}
public void method_a(){
a.method_a();
}
public void method_b(){
a.method_b();
}
public void method_c(){
a.method_c();
System.out.println("this is method c which has been enhanced...");
}
}
//demo
public class Demo1 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
A a = new A();
B b = new B(a);
b.method_a();
b.method_b();
b.method_c();
}
}
//输出结果
this is method a
this is method b
this is method c
this is method c which has been enhanced...