了解java中的instanceof以及if条件?

MKo*_*Kod 3 java instanceof

我不确定树(引用变量)如何在我的示例程序53,00中成为对象Tree的实例?我期待"Pine"和"oops"作为输出,但为什么"Tree"包含在输出中?我还没有给Tree tree = new Tree().

    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" );  
    }  
}
Run Code Online (Sandbox Code Playgroud)

Kep*_*pil 6

既然是a Pine或者Oak也是IS-A Tree,tree instanceof Tree无论treeTree,Pine还是,你都会返回Oak.
您可以InheritanceJava教程中阅读更多内容.