How can this program allow two class A implements Foo

SunScreenCert
SunScreenCert used Ask the Experts™
on
package test1;

interface Foo {
       int bar();
       }
      
       public class Beta {
      
       class A implements Foo {
       public int bar() { return 1; }
       }
      
       public int fubar( Foo foo ) { return foo.bar(); }
      
       public void testFoo() {
      
       class A implements Foo {
       public int bar() { return 2; }
       }
       System.out.println( fubar( new A() ) );
       }
      
       public static void main( String[] argv ) {
       new Beta().testFoo();
       }
       }
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Chief Technology Officer
Most Valuable Expert 2011
Commented:
They have different scopes.  You have one defined under Beta class directly whereas the other in the testFoo method.
a_b
Top Expert 2009
Commented:
The class inside Beta can only be seen by Beta, since it is an inner class.

The second class A is however visible to others.

Kevin CrossChief Technology Officer
Most Valuable Expert 2011
Commented:
More correctly, as a_b pointed out the A under Beta is visible to that class, but the second A is only visible to the testFoo method and hides the previous A implementation.  Therefore, when A is called from testFoo you will get the second implementation and not the first.
Top Expert 2009
Commented:
Its always a good idea to format your code with indentation, then you can see the scoping levels. When I try to understand a piece of code the first thing I do is make sure it is formatted.


// outer scope
{
   // scope level 1
   {
       // scope level 2
       {
           // scope level 3
        }

        {
            // scope level 4
        }
   }
}

Scope levels 3 and 4, though at the same nesting level, are different scopes.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial