2

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(); } } 

4 Answers 4

5

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

Sign up to request clarification or add additional context in comments.

4 Comments

I think the confusion may be caused because the call to "new A()" is happening within the context of the testFoo() method, not fubar().
+1 for speedy correct response. But @Neal, I like to avoid the term 'redefine' because in some other languages, you can actually redefine the method itself. I like the term 'hide'. Thoughts?
@Dilum, yes, but how do you put hide in this context?
I guess something along the lines of 'within Beta.testFoo(), the inner class Beta.A is hidden by the method-scoped inner class A, because the name is re-used.'
3

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.

Comments

0

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

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

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.