What will be the output of the program?

public class Foo {
 Foo() {
  System.out.print("foo");
 }
 class Bar {
  Bar() {
   System.out.print("bat");
  }
  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"


Correct Option: C

AI Explanation

To determine the output of the program, let's go through the code step by step:

  1. The program defines a class named Foo.
  2. Inside Foo, a constructor Foo() is defined, which prints "foo" when an object of Foo is created.
  3. Inside Foo, another class named Bar is defined.
  4. Inside Bar, a constructor Bar() is defined, which prints "bat" when an object of Bar is created.
  5. Inside Bar, a method go() is defined, which prints "hi".
  6. The main method is defined inside Foo and is the starting point of the program.
  7. In the main method, an object f of Foo is created, which prints "foo" when created.
  8. Next, the makeBar() method is called on f.
  9. Inside the makeBar() method, a new anonymous object of Bar is created using the syntax (new Bar() {}). This object is created and its constructor is called, printing "bat".
  10. Then, the go() method is called on this new object, printing "hi".

Therefore, the output of the program will be "foobarhi", which corresponds to option C.

Find more quizzes: