Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a member of a nested class, that is hidden by a member of the outer class

I have a source-code generator that risks generating the following type of code (just an example):

public class Outer {
    public static final Object Inner = new Object();

    public static class Inner {
        public static final Object Help = new Object();
    }

    public static void main(String[] args) {
        System.out.println(Outer.Inner.Help);
        //                             ^^^^ Cannot access Help
    }
}

In the above example, Inner is ambiguously defined inside of Outer. Outer.Inner can be both a nested class, and a static member. It seems as though both javac and Eclipse compilers cannot dereference Outer.Inner.Help. How can I access Help?

Remember, the above code is generated, so renaming things is not a (simple) option.

like image 781
Lukas Eder Avatar asked May 28 '12 10:05

Lukas Eder


People also ask

Can we access to private members of outer class with the concept of inner classes?

If the inner class defined as private and protected, can outer class access the members of inner class? Yes. These qualifiers will only affect the visibility of the inner class in classes that derive from the outer class.

What all are can be accessed from non-static nested classes?

Explanation: The non-static nested class can access all the members of the enclosing class. All the data members and member functions can be accessed from the nested class. Even if the members are private, they can be accessed.

How do you access the outer class variable in an inner class?

If you want your inner class to access outer class instance variables then in the constructor for the inner class, include an argument that is a reference to the outer class instance. The outer class invokes the inner class constructor passing this as that argument.

How do you access members of an inner class?

notation to access the nested class and its members. Using the nested class will make your code more readable and provide better encapsulation. Non-static nested classes (inner classes) have access to other members of the outer/enclosing class, even if they are declared private.


1 Answers

The following works for me (with a warning about accessing static members in a non-static way):

public static void main(String[] args) {
    System.out.println(((Inner)null).Help);
}
like image 167
NPE Avatar answered Oct 31 '22 00:10

NPE