I believe you're confusing object instances with types. What you have declared is two nested types. That is not the same as two nested object instances.
The keyword this
has no meaning when operating with types. It only takes on meaning when dealing with object instances. So, if you're trying to call an instance method of the outer type from the inner type then you need a reference to an instance of the outer type.
However, if you make the method of the outer type static then you can invoke the static method from the nested type without needing a reference to an instance of the outer type. Just keep in mind that if you do that, the method is "the same for all instances" - meaning that it shares any state with all instances of the OuterClass - so it can only access static members of the type.
In the example below, the outerMethod
is declared static, and as such it can be called from the nested type without needing a reference to an instance of OuterClass. However, by doing that, it can no longer access the private instance member data
(without a reference to an instance of course). You could declare a static member staticData
and access that instead, but just keep in mind that that member will be shared by all instances of OuterClass, and by all invokations of outerMethod.
public class OuterClass {
String data; // instance member - can not be accessed from static methods
// without a reference to an instance of OuterClass
static String staticData; // shared by all instances of OuterClass, and subsequently
// by all invocations of outerMethod
// By making this method static you can invoke it from the nested type
// without needing a reference to an instance of OuterClass. However, you can
// no longer use `this` inside the method now because it's a static method of
// the type OuterClass
public static void outerMethod(String data) {
//this.data = data; --- will not work anymore
// could use a static field instead (shared by all instances)
staticData = data;
}
public enum InnerEnum {
OPTION1("someData"),
OPTION2("otherData");
InnerEnum(String data) {
// Calling the static method on the outer type
OuterClass.outerMethod(data);
}
}
}