java - How exactly does the instanceof method work? and why is it not working in my code shown below? -
this question has answer here:
so have defined main class shown below , have defined words class , sentence class. note program should return false when ran. however, getting "incompatible conditional operand types words , sentence" error when run it. isn't how instanceof operator used or confused? how can program modified run without crashing?
public class main{ public static void main (string[] args){ words example = new words("heyo"); sentence ex = new sentence("wats dog"); system.out.println(example instanceof sentence); } }
if variable running instanceof
on can't of same type class supply operator, code won't compile.
since example
of type words
, not sub-class or super-class of sentence
, instanceof
cannot applied on example
, sentence
.
here's jls 15.20.2 says expression "relationalexpression instanceof referencetype":
if cast of relationalexpression referencetype rejected compile-time error, instanceof relational expression likewise produces compile-time error. in such situation, result of instanceof expression never true.
at run time, result of instanceof operator true if value of relationalexpression not null , reference cast (§15.16) referencetype without raising classcastexception. otherwise result false.
Comments
Post a Comment