Sivanagaiah
Sivanagaiah

Reputation: 153

Output of Java program

I am a Java beginner. Can anyone explain why is it printing output 2?

interface Foo {
    int bar();
}

public class Beta {
    class A implements Foo {
        public int bar() {
            return 1;
        }
    }

    public int fubar(final Foo foo) {
        return foo.bar();
    }

    public void testFoo()// 2
    {
        class A implements Foo {
            public int bar() {
                return 2;
            }
        }
        System.out.println(fubar(new A()));
    }

    public static void main(String[] args) {
        new Beta().testFoo();
    }
}

Upvotes: 2

Views: 552

Answers (4)

MByD
MByD

Reputation: 137352

Because the innermost definition of A is in the testFoo() method, and its method bar() return 2.

You may also find the answer to my question from today interesting.

Upvotes: 3

Dilum Ranatunga
Dilum Ranatunga

Reputation: 13374

There are many places in java where you can hide a broader name with a more local name. This is true of parameters vs member variables, class names etc. In your case, you are hiding Beta.A with the A you defined in the method.

Upvotes: 0

Kal
Kal

Reputation: 24910

When you say, System.out.println(fubar(new A()));

the class A created is the one defined inside testFoo().

Upvotes: 0

Naftali
Naftali

Reputation: 146310

That is because you redefined Class A here:

    class A implements Foo {
        public int bar() {
            return 2;
        }
    }
    System.out.println(fubar(new A()));

So when you do return foo.bar(); you return 2

Upvotes: 5

Related Questions