Puzzle on Inner Classes and Class Hiding

2019-09-21 06:44发布

问题:

I have a sample code to solve which is based on inner classes:

package inner;

class A {
    void m() {
        System.out.println("Outer");
    }
}

public class TestInner {
    public static void main(String[] args) {
        new TestInner().go();       
    }

    private void go() {
        new A().m();
        class A{
            void m(){
                System.out.println("Inner");
            }
        }
        new A().m();
    }
    class A{
            void m(){
            System.out.println("Middle");
        }
    }
}

The output given by above sample code is:

Middle 
Inner

And my question is, given that I dont want to use the package name to create an object, how can I print the output as:

Outer
Inner

回答1:

Since using a package is so obviously the answer, I assume you are looking for something obtuse.

You can add an outer class and call that.

class B extends A { }

// in TestInner.go()
    new B().m();
    class A{
        void m(){
            System.out.println("Inner");
        }
    }
    new A().m();


回答2:

public class TestInner {
public static void main(String[] args) {
    new TestInner().go();       
}

private void go() {
    new inner.A().m();        //will produce output "Outer"
    class A{
        void m(){
            System.out.println("Inner");
        }
    }
    new A().m();             //will produce output "Inner"
}
class A{
        void m(){
        System.out.println("Middle");
    }
}