简体   繁体   English

对于原始数据类型这怎么可能?

[英]How is this possible for primitive data type?

Do primitive data type extend Object class? 原始数据类型是否扩展了Object类? If no, then how this piece of code possible 如果否,那么这段代码怎么可能

long l=4567;
Object o=l;
System.out.println(o);

Why dont we get any compile error? 为什么我们没有任何编译错误?

It is called auto-boxing and was introduced in Java 5. 它称为自动装箱,是Java 5中引入的。

The compiler will detect that you use a primitive where you should be using an object and inserts the following transformation automatically: 编译器将检测到您在应使用对象的地方使用了原语,并自动插入以下转换:

Object o = Long.valueOf(l);

It also works the other way around (auto-unboxing): 它也可以通过其他方式工作(自动拆箱):

Long one = 1;

System.out.println(one + 2);
// gets compiled to
System.out.println(one.longValue() + 2);

The primitive long gets auto boxed into an Object of type Long. long原语会自动装箱成Long类型的Object。 This is very useful as the primitives will automatically be converted to and from objects as needed. 这非常有用,因为基元将根据需要自动在对象之间进行转换。 See here for some details - http://docs.oracle.com/javase/tutorial/java/data/numberclasses.html 有关详细信息,请参见此处-http://docs.oracle.com/javase/tutorial/java/data/numberclasses.html

And http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html 还有http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM