Discussion :: Inner Classes
-
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 */
Answer : Option C
Explanation :
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".
Be The First To Comment