Java Programming - Java.lang Class - Discussion

Discussion Forum : Java.lang Class - Finding the output (Q.No. 22)
22.
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" ); 
        else 
            System.out.println ("Oops "); 
    } 
}
Pine
Tree
Forest
Oops
Answer: Option
Explanation:

The program prints "Pine".

Discussion:
6 comments Page 1 of 1.

Manoj Dhingra said:   2 years ago
Here we can use the Concept of Dynamic Dispatch.

Burt777 said:   9 years ago
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?

Sami vanzara said:   10 years ago
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.

K Amit said:   10 years ago
Oak Class and Pine Class are extending same Class Tree (Multiple inheritance).

Is it possible with class?

Aqui said:   10 years ago
I have not understood it yet.

Mohit said:   1 decade ago
As the object passed to ref var of tree is of pine.

So pine satisfies the result.

Post your comments here:

Your comments will be displayed after verification.