java - The 'instanceof' operator behaves differently for interfaces and classes -
i know regarding following behavior of instanceof
operator in java.
interface c {} class b {} public class { public static void main(string args[]) { b obj = new b(); system.out.println(obj instanceof a); //gives compiler error system.out.println(obj instanceof c); //gives false output } }
why so? there no relation between interface c
, class b
, gives false whereas in case of obj instanceof a
gives compiler error?
because java has no multiple class inheritance it's absolutely known during compilation obj
object of type b
cannot subtype of a
. on other hand possibly can subtype of interface c
, example in case:
interface c {} class b {} class d extends b implements c {} public class { public static void main(string args[]) { b obj = new d(); system.out.println(obj instanceof c); //compiles , gives true output } }
so looking @ obj instanceof c
expression compiler cannot tell in advance whether true or false, looking @ obj instanceof a
knows false, meaningless , helps prevent error. if still want have meaningless check in program, can add explicit casting object
:
system.out.println(((object)obj) instanceof a); //compiles fine
Comments
Post a Comment