• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

Doubt in instanceof

 
Ranch Hand
Posts: 274
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 621
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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!!!
 
Ranch Hand
Posts: 169
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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..

https://coderanch.com/t/264076/java-programmer-SCJP/certification/instanceof-Comparison
 
reply
    Bookmark Topic Watch Topic
  • New Topic