Java Programming - Inner Classes - Discussion

Discussion :: Inner Classes - Finding the output (Q.No.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 */
} /* class HorseTest ends */

[A]. An exception occurs at runtime at line 10.
[B]. It prints "Zippo".
[C]. Compilation fails because of an error on line 7.
[D]. Compilation fails because of an error on line 13.

Answer: Option B


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.

Avi said: (May 14, 2013)  
Is this "public Horse(String s)" Parametric constructor?

Sai said: (Dec 26, 2013)  
There is no default constructor. So I suspect answer is compilation fails.

Mani said: (Jan 27, 2014)  
Horse h = (Horse) obj;

How it works? Can any one explain.

Cutie said: (Jun 14, 2016)  

I also want to ask the same question. Can anyone answer this? Please.

Suresh N said: (Apr 7, 2017)  
Output is compilation error.

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at HorseTest.main(

Anyone help me to resolve it.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.