It's not a secret anymore!*
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
Author

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)
Ans:A,B,D

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

Regards,
Gitesh
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 it...it will definately help you..

http://www.coderanch.com/t/264076/java-programmer-SCJP/certification/instanceof-Comparison


"History would be kind to me, for I intend to write it."
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Doubt in instanceof
 
Similar Threads
MindQ's mock 32
mock question
instance of operator
instanceOf??
Inheritance