Search code examples
javafileexternalnested-class

Nested/Inner class in external file


I have a class MyClass and an inner class MyNestedClass like this:

public class MyClass {
  ...
  public class MyNestedClass {
    ...
  }
}

Both classes are very long. Because of that i'd like to seperate them in two different files, without breaking the hierarchy. This is because the nested class shouldn't be visible to the programmer who uses MyClass.

Is there a way to achieve that?


Solution

  • You can make the inner class package private which means that it will only be accessible from other classes in exactly the same package. This is also done quite frequently for hidden classes inside the standard JDK packages like java.lang or java.util.

    in pkg/MyClass.java

    public class MyClass {
      ...
    }
    

    in pkg/MyHiddenClass.java

    class MyHiddenClass {
    
      final MyClass outer;
    
      MyHiddenClass( MyClass outer )
      {
          this.outer = outer;
      }
      ...
    }
    

    Now when you want to access methods or variables of the outer class you need to prefix them with outer. but you get essentially the same functionality as before when the reference to the outer instance was synthetically created by the compiler.