friends, RHE book states following compile-time rule for Object ref casting, Oldtype: non-final class & Newtype : Array -> Newtype must be Object
Oldtype: Array & Newtype: non-final class -> Oldtype must be Object
Object --> Fruit --> Citrus (implements Squeezable) -->Lemon -->Tangelo -->Grapefruit Tangelo tang = new Tangelo(); Object objAry; objAry = tang; // as per rule this should complile, but won't However, Object ob = tang; //This will compile Can somebody clarify this rule. sujit
Sujit, I don't see any problem with the reasoning. You are complaining about trying to convert an non-final class to an array. That is not possible in Java. Your third line gives you the answer: non-final class to Array -> Newtype must be Object. You are trying to read it with the last word being Array instead of Object! In Java an array is an object therefore we can always do the following: int intArray = new int; Object ob = intArray or MyClass c = new MyClass(); Object ob = c; We can not however, do the following: int intArray = new int; Object obArr = intArray; or MyClass c = new MyClass(); Object obArr = c; In your case you could have performed the following:
Sujit, I have the same doubt. RH rule for casting reference: Oldtype: non-final class & Newtype : Array -> Newtype must be Object When Newtype is first said as Array, how come the rule is that Newtype must be Object? We are talking about array as new type, not Object! Then we try Object as new type, wrong too. You may argue that an array is an object; but an object of Object type is not always an array. So I think the book should make this more clear.
What RHE is saying is that if you are trying to convert a non-final class to an array, the best you can do is convert it to an Object, the superclass of an array. Basically that means you can't convert a non-final class to an Array.
Jane, Thanks. The issue here is not about whether you can cast an array to an array. It is about one rule in the book talking about casting from a non-final class to an array. I think the discussion so far has made that issue very clear. --Howard
Just to add to the discussion, we've had a handful of readers write in and report our explanation here as an error. Possibly the rule is too terse at first sight, but it is correct. Thanks to Bill and Manfred for explaining our intent so clearly!