What role does instanceof operator play in the above code?
In a tutorial for instanceof te below was given: if (objectA instanceof objectB)will yield true if objectA can be upcast to objectB.
ObjectA can be upcast to objectB.means what with reference to above code.
Joined: Jan 01, 2007
Have you tried looking at the java documentation for instanceof? Maybe a google search? The top entry on my google search just came back with an interesting discussion on the sun java forums.
Basicly, it does what it says. It returns true is objectB is an instance of objectA.
Upcasting simply means you are casting the object "up" the inheritance tree. If you are having trouble with this, I really do suggest you go to the Java site and read up on Object casting, it is a fundemental concept.
Give C extends A, and B extends Object, what do you think the result of these would be?
Joined: Oct 13, 2005
It won't compile because you haven't declared a variable "val."
If you had used "value" instead, value is a String which cannot be upcast or downcast to Integer, so it prevents a ClassCastException.
It also prevents the body of the "if" block executing, which means the new_val variable is never initialised, which means it is never returned, which means that not every path through the method returns a value, which means it won't compile. And even if you did get to return a value, it would be out of scope after the "if" block so it still won't compile.