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.
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.
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.
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With