• 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Cast

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,
Please look at the following code, class CClass does not implement interface Face, why there is no compilation error at comment line 1.?
interface Face{
void method();
}
class CFace implements Face{
public void method(){}
}
class CClass {
void method(){}
}
public class FaceTest{
public static void main(String[] args){
Face f = new CFace();
CClass c1= (CClass)f; //1.
}
}

Thanks in advance,
Erin
 
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is because this is what JLS specifies. You might wanna have a look at the casting and conversion tables given in RHE. I find them very handy. So, there's no compilation error supposed to occur. However, there WILL be a runtime error in this case. Also, there would have been a compiler error if you hadn't use the casting.
Thanks,
Aman

[This message has been edited by Amandeep Waraich (edited September 09, 2000).]
 
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Because the compiler has no way to tell whether 'f' can or cannot possibly refer to an object of class CClass. And as there is an explicit cast, it believes the coder that the object refered to by 'f' 'may' actually refer to an object of class CCLass.
The point here is, if a compiler can figure out that some thing is just not possible in any case then it generates an error. For eg. had 'f' been of class CFace instead of interface Face, it would know that f can NEVER point to an object of class CClass as there is no relation between them ( none is a sub/super class of the other). So it would generate an error.
But as f is of interface Face, it just can't figure out whether
it can/cannot point to an object of class CClass. So it passes it. It will fail at run time though!
HTH,
Paul.
------------------
http://pages.about.com/jqplus
Get Certified, Guaranteed!
 
reply
    Bookmark Topic Watch Topic
  • New Topic