包装类--java

包装类:

        当为了增强某类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...

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值