Java Programming - Inner Classes - Discussion
Discussion Forum : Inner Classes - Finding the output (Q.No. 2)
2.
What will be the output of the program?
public class HorseTest
{
public static void main (String [] args)
{
class Horse
{
public String name; /* Line 7 */
public Horse(String s)
{
name = s;
}
} /* class Horse ends */
Object obj = new Horse("Zippo"); /* Line 13 */
Horse h = (Horse) obj; /* Line 14 */
System.out.println(h.name);
}
} /* class HorseTest ends */
Answer: Option
Explanation:
The code in the HorseTest class is perfectly legal. Line 13 creates an instance of the method-local inner class Horse, using a reference variable declared as type Object. Line 14 casts the Horse object to a Horse reference variable, which allows line 15 to compile. If line 14 were removed, the HorseTest code would not compile, because class Object does not have a name variable.
Discussion:
5 comments Page 1 of 1.
Suresh N said:
6 years ago
Output is compilation error.
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at HorseTest.main(HorseTest.java:3).
Anyone help me to resolve it.
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at HorseTest.main(HorseTest.java:3).
Anyone help me to resolve it.
Cutie said:
7 years ago
@Mani.
I also want to ask the same question. Can anyone answer this? Please.
I also want to ask the same question. Can anyone answer this? Please.
Mani said:
9 years ago
Horse h = (Horse) obj;
How it works? Can any one explain.
How it works? Can any one explain.
Sai said:
9 years ago
There is no default constructor. So I suspect answer is compilation fails.
Avi said:
1 decade ago
Is this "public Horse(String s)" Parametric constructor?
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers