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 ");
}
}
Answer: Option
Explanation:
The program prints "Pine".
Discussion:
6 comments Page 1 of 1.
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.
So, in if condition instanceof return true and execute, display output pine.
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?
Pine pine = new Pine();
Are they interchangeable? Or why is it wrong? Or what's the difference?
K Amit said:
10 years ago
Oak Class and Pine Class are extending same Class Tree (Multiple inheritance).
Is it possible with class?
Is it possible with class?
Mohit said:
1 decade ago
As the object passed to ref var of tree is of pine.
So pine satisfies the result.
So pine satisfies the result.
Manoj Dhingra said:
2 years ago
Here we can use the Concept of Dynamic Dispatch.
Aqui said:
10 years ago
I have not understood it yet.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers