Java Programming - Inner Classes - Discussion

Discussion Forum : Inner Classes - Finding the output (Q.No. 1)
1.
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 */
Compilation fails.
An error occurs at runtime.
It prints "foobarhi"
It prints "barhi"
Answer: Option
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".

Discussion:
15 comments Page 2 of 2.

Sohi said:   1 decade ago
@Chandni.

Its just to confuse the developer but syntax is creating an anonymous subclass of Type Bar and Using Bar class's(which is super class of Anonymous class)go() method.

Jalpesh said:   1 decade ago
@Keshav kushwaha : you should rename your java class file name as Foo.

Keshav kushwaha said:   1 decade ago
Compilation fail : "The public type Foo must be defined in its own file".

Chandni said:   1 decade ago
Why use{} after calling of Bar() in makeBar() method?

Vidur Punj said:   1 decade ago
(new Bar() {}).go();
It should produce compile time error ;


Post your comments here:

Your comments will be displayed after verification.