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" );
}
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With