简体   繁体   中英

How is this possible for primitive data type?

Do primitive data type extend Object class? 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.

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. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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