Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

java - SCJP: can't widen and then box, but you can box and then widen

I'm studying for the SCJP exam and I ran into an issue I can't really wrap my head around.

The book says you can't widen and then box, but you can box and then widen. The example for not being able to box is a method expecting a Long and the method being invoked with a byte.

Their explanation is:

Think about it…if it tried to box first, the byte would have been converted to a Byte. Now we're back to trying to widen a Byte to a Long, and of course, the IS-A test fails.

But that sounds like box and then widen and not widen and then box to me.

Could anyone clarify the whole box and widen vs widen and box for me because as it stands the book isn't exactly clear on the issue.

Edit: To clarify: I'm talking about pages 252 and 253 of the SCJP sun certified programmer for java 6 book. http://books.google.be/books?id=Eh5NcvegzMkC&pg=PA252#v=onepage&q&f=false

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

the language is confusing.

Basically you can't go in this fashion:
byte -> Byte -> Long
because Byte and Long don't share an is-a relationship.
So, it tries to do this:
byte -> long -> Long
But it can't do that either(apparently due to compiler limitations). So, it fails and throws an error.

But, on the other hand you CAN do this:
byte -> Byte -> Object
because Byte is-an Object.

consider 2 functions and a byte variable:

toLong(Long x)
toObject(Object x)
byte b = 5;

Then this statement will be illegal:
toLong(b);
// because b -> new Byte(b) -> new Long(new Byte(b)) is illegal.
AND byte -> long -> Long can't be done due to compiler limitations.

but this statement is legal:
toObject(b);
// because b -> new Byte(b) -> new Object(new Byte(b)) is legal.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...