包装类的声明 [英] Declaration of wrapper classes
问题描述
这个问题是一个问题的延续 一个字符串怎么能使用初始化""?
This question is in continuation to a question How can a string be initialized using " "?
我想引起您的注意,即使是Integer
、Double
、Character
、Float
、Boolean
包装类也可以用与 String
声明相同的方式声明:
I would like to raise your attentation that even Integer
, Double
, Character
, Float
, Boolean
wrapper class can also be declared in the same way String
is declared like:
String s = "Test string"
Integer i = 10; //valid
Double d = 10.00; //valid
Boolean b = true; //valid
这些类是否也像 String
类一样被给予特殊处理.
Does these class are also given special treatment like the String
class.
推荐答案
正如我在之前的回答中指出的那样(如何使用"?)初始化字符串
As I pointed out In my previous answer(How can a string be initialized using " "?)
是的,为了在 OOP 中保留 primitive
类型,设计者使用 Wrappers
在 primitives
和 Object's
之间架起了桥梁他们有特殊待遇.
Yes, to retain primitive
types in an OOP, designers made bridge between primitives
and Object's
with Wrappers
and they have a special treatment.
原因很清楚在文档中解释了.
然而,使用对象代替原语是有原因的,Java 平台为每种原语数据类型提供了包装类.这些类将原语包装"在一个对象中.通常,包装是由编译器完成的——如果您在需要对象的地方使用原语,编译器会为您在其包装类中装箱该原语.类似地,如果您在需要基元时使用数字对象,则编译器会为您拆箱该对象.有关详细信息,请参阅自动装箱和取消装箱
There are, however, reasons to use objects in place of primitives, and the Java platform provides wrapper classes for each of the primitive data types. These classes "wrap" the primitive in an object. Often, the wrapping is done by the compiler—if you use a primitive where an object is expected, the compiler boxes the primitive in its wrapper class for you. Similarly, if you use a number object when a primitive is expected, the compiler unboxes the object for you. For more information, see Autoboxing and Unboxing
我们在程序中广泛使用 primitives
,因此允许像
We use primitives
extensively in our programs, So it might be a design decision to allowing syntax like
Integer i = 10; //primitive style
然后 memory
在 compile
时间为 i 分配自身,因为它是 primitive
类型,当他们发现使用 Wrapper
类型声明和 赋值运算符
=
Then memory
allocates at compile
time itself for i since it is a primitive
type, when they found with Wrapper
type declarations with an Assignment operator
=
语法明智,这更方便和快乐(至少对我来说:)).
Syntax wise ,that is more handy and happy(at least for me :)).
比写作,
Integer i = new Integer(10); //Object creation style
这篇关于包装类的声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!