• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

explicit casting

 
Ranch Hand
Posts: 167
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In Ch 4 of RHE, it says that any reference of non-final, non-array class type can always to assigned to reference of any interface, and vice versa. Is that true?
Also, an object of the reference type array can be assigned to a interface reference type only if that interface type is Cloneable. But, when an object of an interface reference type is assigned to an array reference type, compiler will signal error. Why is it not compilable vice versa?
Thanks!
 
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
First of all, I guess, you need to go through the chapter 4 in detail once more. Or refer to JLS "Conversions and Promotions" for detailed explanations regarding this. Anyway, I have provided a summary for all your questions here:
1. Conversion from any subclass reference to its superclass reference is possible without casting.For eg.,
String s=new String("Hello");
Object o=s;//ok
2. Conversion from any reference object to its implementing interface is possible without casting. For eg.,
Thread t=new Thread();
Runnable r=t;//ok because, Thread class implements Runnable Interface
3. Any reference object can be assigned the null parameter.
String s=null;
4. A reference of type Object can be assigned anything, viz., any class reference, any interface type or any array reference
eg.,
String s=new String();
Object o=s;
o=Runnable r;
int a[]={1,2,3};
o=a;
All the above are possible without a cast.
5. An array reference can be assigned to the interface Cloneable since any type of array is considered to implement the interface "Cloneable".
int a[]={1,2,3};
Cloneable c=a;//Ok
Runnable r=a;//Wrong!
Anything other than the above would result in a compile-time error in case an explicit cast is not provided in some of these cases.
Hope it is clear now.
Aparna R
 
reply
    Bookmark Topic Watch Topic
  • New Topic