Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt in instanceof Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt in instanceof" Watch "Doubt in instanceof" New topic

Doubt in instanceof

Gitesh Ramchandani
Ranch Hand

Joined: Feb 28, 2007
Posts: 274
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)

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

dhwani mathur
Ranch Hand

Joined: May 08, 2007
Posts: 621
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

Joined: Oct 29, 2006
Posts: 169
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 will definately help you..

"History would be kind to me, for I intend to write it."
I agree. Here's the link:
subject: Doubt in instanceof
It's not a secret anymore!