This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

MindQ's mock 32  RSS feed

prasanna perera
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All!
Q. 32 from MindQ's mock:
class Tree{}
class Pine extends Tree{}
class Oak extends Tree{}
public class Forest
{ public static void main( String[] args )
{ Tree tree = new Pine();
if( tree instanceof Pine )
System.out.println( "Pine" );
if( tree instanceof Tree )
System.out.println( "Tree" );
if( tree instanceof Oak )
System.out.println( "Oak" );
else System.out.println( "Oops" );
Select all choices that will be printed:
a) Pine
b) Tree
c) Forest
d) Oops
e) (nothing printed)
I compiled the code and found that a,b,d are correct. I was wondering how b is correct as through dynamic binding tree would have a Pine object. So
if( tree instanceof Tree )
if( Pine instanceof Tree )
which evaluates to false ?
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
dear prasanna.. take a heavy breadth...and read on..
your evaluation of the expression that
>if( tree instanceof Tree )
>if( Pine instanceof Tree )
>which evaluates to false ?
is wrong in some good sense.
/ \
pine oak
read on...
now the code creates a pine object.
assigns a reference to the object to an tree reference
Tree tree= new Pine();
and consider: tree instanceof pine
and have you wondered what does this all means?
it means that the pine object can act not only as a pine but also as a tree object.since it inherits all the features of tree.
this is known as polymorphism in object oriented programming.
i.e an object can exhibit many(poly) forms.
thus and pine is an instance of tree therefore
tree instanceof pine is true.
and ofcourse
tree is an instanceof Tree
therefore tree instanceof Tree is true
but u see...
tree instanceof oak is not true why?
because tree object cannot exhibit the same behavior as that of an oak. getting my point? oak and pine are two diffrent classes and hence diffrent behaviour.
we say x instanceof y whenever:
x can exhibit all behaviour as that of y.
-good luck
and do take care.

Smitha Krishna
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
True, tree would have an instance of Pine object
which happens to be a descendant of class Tree. The instanceof operator also returns true if the LHS(left hand side) implements the RHS where the RHS is an Interface.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!