什么是包装器类? 这样的类有什么用处呢?


当前回答

顾名思义:一个类将另一个类或API的功能“包装”在一个更简单或只是不同的API中。

参见:适配器模式、门面模式

其他回答

顾名思义:一个类将另一个类或API的功能“包装”在一个更简单或只是不同的API中。

参见:适配器模式、门面模式

包装类是用于包装另一个类的类,以便在客户端和被包装的原始类之间添加间接和抽象层。

In general, a wrapper class is any class which "wraps" or "encapsulates" the functionality of another class or component. These are useful by providing a level of abstraction from the implementation of the underlying class or component; for example, wrapper classes that wrap COM components can manage the process of invoking the COM component without bothering the calling code with it. They can also simplify the use of the underlying object by reducing the number interface points involved; frequently, this makes for more secure use of underlying components.

包装器类是唯一用于保存某些东西并向其添加一些功能的类。 在Java中,由于原语(如int,float,char…)不是对象,所以如果你想把它们当作一个对象,那么你必须使用包装类。 假设你想创建一个int型的Vector,问题是Vector只保存对象而不是原语。所以你要做的就是把所有的整型放在一个Integer包装器中并使用它。例子:

int number = 5;
Integer numberWrapped = new Integer(number);
//now you have the int in an object.
//and this is how to access the int value that is being wrapped.
int again = numberWrapped.intValue();

Java编程为每个基元数据类型提供包装类,用于将基元数据类型转换为包装类的对应对象。