Multiple choice

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 */

  1. Compilation fails.

  2. An error occurs at runtime.

  3. It prints "foobarhi"

  4. It prints "barhi"

Reveal answer Fill a bubble to check yourself
C Correct answer
Explanation

Option C is correct because first the Foo instance is created, which means the Fooconstructor 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".