Inner Classes - Programming

Q1:

What will be the output of the program?
public class Foo 
{
    Foo() 
    {
        System.out.print('foo');
    }
    
class Bar
{
    Bar() 
    {
        System.out.print('bar');
    }
    public void go() 
    {
        System.out.print('hi');
    }
} /* class Bar ends */

    public static void main (String [] args) 
    {
        Foo f = new Foo();
        f.makeBar();
    }
    void makeBar() 
    {
        (new Bar() {}).go();
    }
}/* class Foo ends */

A Compilation fails.

B An error occurs at runtime.

C It prints "foobarhi"

D It prints "barhi"

ANS:A - Compilation fails.

Option C is correct because first the Foo instance is created, which means the Foo constructor runs and prints 'foo'. Next, the makeBar() method is invoked which creates a Bar, which means the Bar constructor runs and prints 'bar', and finally the go() method is invoked on the new Bar instance, which means the go() method prints 'hi'.