开发者

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() {
    开发者_JS百科        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();
    }
}


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


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.


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

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜