aspose file tools*
The moose likes Java in General and the fly likes compiler inconvertible types vs ClassCastException Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "compiler inconvertible types vs ClassCastException" Watch "compiler inconvertible types vs ClassCastException" New topic
Author

compiler inconvertible types vs ClassCastException

Radu Grigoras
Greenhorn

Joined: Apr 18, 2013
Posts: 3
Hello,

A few days ago a stumbled upon tricky SCJP question and I couldn't find the answer . Why the compiler won't let me cast a String object as it would for an ArrayList object?


Thanks.
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

You should note that the type of the reference that the Compiler does not Catch is List, not ArrayList. Do you see why that may make a difference?


Steve
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38881
    
  23
And welcome to the Ranch
Radu Grigoras
Greenhorn

Joined: Apr 18, 2013
Posts: 3
Thanks

Exactly that the difference:

interface Interf {}
...
Interf i =new Interf(){};
A a= (A)i;//class cast ex
a= (A) new Interf(){}; //compiler inconvertible types

Thanks .
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

So do you understand why it behaves that way? Or are you still having trouble with it?
Radu Grigoras
Greenhorn

Joined: Apr 18, 2013
Posts: 3
Yes, it's clear. Thanks
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: compiler inconvertible types vs ClassCastException