aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes MindQ's mock 32 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "MindQ Watch "MindQ New topic
Author

MindQ's mock 32

prasanna perera
Greenhorn

Joined: Oct 05, 2000
Posts: 16
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 )
becomes
if( Pine instanceof Tree )
which evaluates to false ?
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
dear prasanna.. take a heavy breadth...and read on..
your evaluation of the expression that
>if( tree instanceof Tree )
>becomes
>if( Pine instanceof Tree )
>which evaluates to false ?
is wrong in some good sense.
Tree
/\
/ \
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.
bye




Smitha Krishna
Greenhorn

Joined: Oct 06, 2000
Posts: 4
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: MindQ's mock 32