Java Customs class instance can't cast to String. Why? -
this question has answer here:
why instance of can cast list can not cast string?
class a{} ... a = new a(); list list = (list)a; //pass string s = (string)a; //compile error
the compiler, according specification, takes declared type of a
account when these checks casts.
so, write:
a = new a();
but compiler considers
a a; // = <something>;
so knows a
cannot string
, since class can have 1 superclass (no multiple inheritance), there can't subclass of class a
string.
but interfaces isn't true. while know class a
doesn't implement list
, there class b
defined this:
class b extends implements list {}
and since compiler considers declared type, must assumes possible assigned new b()
a
.
so, because subclass of a
implement interface list
, compiler can't assume cast list
fails.
of course cast fail in practice though - @ runtime. not @ compile time.
Comments
Post a Comment