Java Inner class shadowing external class

2019-06-21 19:38发布

问题:

I took the following code from the K&B book "SCJP Sun Certified Programmer for Java 6 Study Guide":

class A { // 1
    void m() { 
        System.out.println("outer"); 
    } 
}

public class TestInners {

    public static void main(String[] args) {

        new TestInners().go();

    }

    void go() {

        new A().m();

        class A { // 2
            void m() { 
                System.out.println("inner"); 
            } 
        }

    }

    class A { // 3
        void m() { 
            System.out.println("middle"); 
        } 
    }
}

As stated in the book, this code prints "middle". I infer that the class declaration marked as "3" is shadowing the one marked as "1", which is external to TestInners class. If the classes were in different packages, I could resolve the ambiguity by qualifying one of them with the package name. But in this case the classes are not only in the same package but in the same file. How can I get an instance of the external class?

I saw the same question here but the accepted answer implies to modify the code adding an enclosing class to the whole thing. My question is how to get the instance using any type of qualifier or reference, if it's even possible.

回答1:

Assuming your class is in package com.test, all you need to do is use

new com.test.A().m();

using the fully qualified name of the class.

If your classes are in the default package, ie. no package declaration, then you are out of luck and can't access the outer A.



回答2:

In C++, you can explicitly address global scope by prefixing your symbol with ::, however, Java does not have such a thing.

So if you really want to get the outer A, you have to bite the bullet and do some other sort of enclosure, by for example wrapping it in another class or package.

EDIT: Here is another reason why.



回答3:

object of innner-A can't be created before defining it.so use new A().m(); after define innner-A inside go() to access inner class object.

void go() {

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

to access outer-A you have to append package name,in default package it is impossible to access outer-A.