java - Cast reference of known type to an interface outside of type's hierarchy -


say have clean class this:

public class {     // stuff } 

and interface this:

public interface g {     // stuff } 

why allowed this:

a = new a(); ((g) a) // no errors thrown 

i can't understand why should possible cast class interface g when have nothing each other. can please explain me?


follow-up. if make following:

public class c implements g {     // stuff } 

this won't compile:

((c) a) 

what difference between class implements interface , interface?

edit: compiler-error saying:

cannot cast c

casting means know better compiler what's valid. telling compiler shut , follow lead. compiler can tell in few cases cast invalid, easy fool.

most casts tend object else, such in getting object out of non-genericized collection or when getting remote object using portableremoteobject.narrow. these casts compile because whatever cast (as long it's object, , not primitive) valid subclass of object.

there rules casting in java language specification in section reference type casting (5.5.1). if compiler can figure out there no relationship between classes (the compiler can tell classes different , neither subclass of other) reject cast.

the added example interesting, fails because compiler has enough information tell cast invalid. if change code to:

    a = new a();     g g = (g)a;     object o = a;     c c = (c)o; 

then compiles fine again (even though erroneous).


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -