Java Programming - Java.lang Class - Discussion


What will be the output of the program?

class Tree { } 
class Pine extends Tree { } 
class Oak extends Tree { } 
public class Forest1 
    public static void main (String [] args)
        Tree tree = new Pine(); 
        if( tree instanceof Pine ) 
            System.out.println ("Pine"); 
        else if( tree instanceof Tree ) 
            System.out.println ("Tree"); 
        else if( tree instanceof Oak ) 
            System.out.println ( "Oak" ); 
            System.out.println ("Oops "); 

[A]. Pine
[B]. Tree
[C]. Forest
[D]. Oops

Answer: Option A


The program prints "Pine".

Mohit said: (Dec 2, 2011)  
As the object passed to ref var of tree is of pine.

So pine satisfies the result.

Aqui said: (Sep 14, 2015)  
I have not understood it yet.

K Amit said: (Nov 26, 2015)  
Oak Class and Pine Class are extending same Class Tree (Multiple inheritance).

Is it possible with class?

Sami Vanzara said: (Feb 16, 2016)  
As object pine is created in Tree class type variable, tree variable pointing to Pine object so in if condition pine is subclass of its own.

So, in if condition instanceof return true and execute, display output pine.

Burt777 said: (Jan 6, 2017)  
I would have expected line 8 to read:

Pine pine = new Pine();

Are they interchangeable? Or why is it wrong? Or what's the difference?

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.