Nested/Inner class in external file

后端 未结 6 697
醉话见心
醉话见心 2021-01-07 15:57

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

public class MyClass {
  ...
  public class MyNestedClass {
             


        
6条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-07 16:48

    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.

提交回复
热议问题