Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt in instanceof

 
Gitesh Ramchandani
Ranch Hand
Posts: 274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
source MinQ-Q32

Consider the following code sample:
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)
Ans:A,B,D

Doubt:Why A, what is the funda behind it?

Regards,
Gitesh
 
dhwani mathur
Ranch Hand
Posts: 621
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok well!!
I think you must see this statement what does
it indicate?


Tree tree = new Pine();

Here Tree is a super class,Pine is a base class
although here tree is a reference variable
of Tree class but its object of Pine........

Hence (tree instanceOf Pine)
gives true!!!
prints "Pine"

I hope it helps!!!
 
Priyam Srivastava
Ranch Hand
Posts: 169
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A is correct because the reference varaible tree is referring to an object of Pine at run time...

there is a healthy discussion done on the tpoic of instanceof in this thread (link below). you can have a look at it...it will definately help you..

http://www.coderanch.com/t/264076/java-programmer-SCJP/certification/instanceof-Comparison
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic