Reputation: 823
I am not sure how the tree (reference variable) became instance of object Tree in my sample program 53,00? I am expecting "Pine" and "oops" as output but why "Tree" is included in output? I havent given Tree tree = new Tree() at all.
class Tree{}
class Pine extends Tree{}
class Oak extends Tree{}
public class forrest {
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" );
}
}
Upvotes: 3
Views: 6592
Reputation: 17945
Your class Pine has an implicit constructor (which gets placed there by the compiler unless you manually define your own, in which case your constructor will be used). All subclasses must call their parent class (superclass) as a part of their constructor. Not doing so results in an exception being thrown. So you have an implicit
Pine Pine() { super(); }
Which is calling the implicit constructor of it's superclass (Tree; that is what "super()" does), which looks like
Tree Tree() { super(); }
Which is calling the implicit constructor of it's superclass (Object)...
Therefore, if tree is a Pine, then
tree instanceof Pine
tree instanceof Tree
tree instanceof Object
all return true
Upvotes: 1
Reputation: 4182
As said by Keppil, instanceof returns true on ancestors as well. Based on this, the following will happen:
Tree tree = new Pine()
tree instanceof Pine; // true
tree instanceof Oak; // false
tree instanceof Tree; // true
tree instanceof Object; // true
Object something = new Oak();
something instanceof Pine; // false
something instanceof Oak; // true
something instanceof Tree; // true
something instanceof Object; // true
In fact, instanceof Object will always return true.
Upvotes: 3
Reputation: 5619
Every subclass 'is a' type of its superclass. Since your "tree" is an instance of Pine class extended from Tree class, it is an instance of Tree.
For your coding style, I suggest reading Beware of instanceof operator
Upvotes: 0
Reputation: 834
A child is instance of itself and subtype of its parent class.every class is subType of java.lang.Object class. In your example Pine and Oak are child class of Tree or can be written as Pine and Oak are subType of Tree class so
if( tree instanceof Tree )
is True.
Upvotes: 0
Reputation: 46219
Since a Pine
or an Oak
also IS-A Tree
, your tree instanceof Tree
will return true whether tree
is Tree
, Pine
or Oak
.
You can read more on Inheritance
in the Java Tutorials.
Upvotes: 6