• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

explicit casting  RSS feed

 
Ranch Hand
Posts: 167
  • Mark post as helpful
  • send pies
  • 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
  • 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
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!