Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Inner class shadowing external class

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.

like image 989
DiegoAlfonso Avatar asked Nov 28 '13 15:11

DiegoAlfonso


2 Answers

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.

like image 108
Sotirios Delimanolis Avatar answered Sep 29 '22 22:09

Sotirios Delimanolis


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.

like image 35
Domi Avatar answered Sep 29 '22 21:09

Domi