Search code examples
javainstanceof

Understanding instanceof in java along with if condition?


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" );  
    }  
}

Solution

  • 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.