外部文件中的嵌套/内部类 [英] Nested/Inner class in external file

查看:129
本文介绍了外部文件中的嵌套/内部类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类 MyClass 和一个内部类 MyNestedClass 像这样:

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

这两个类都很长。因为这个我想用两个不同的文件把它们分开,而不是打破层次结构。这是因为使用MyClass的程序员不应该看到嵌套类。



有没有办法达到这个目的?


<解决方案您可以使内部类包私有,这意味着它只能从完全相同的包中的其他类访问。对于标准JDK包(如 java.lang java.util )中的隐藏类, / p>

in pkg / MyClass.java

  public class MyClass {


in pkg / MyHiddenClass.java

  class MyHiddenClass {

final MyClass outer;

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

现在当你想要要访问外部类的方法或变量,你需要用 outer。前缀它们,但是当你对外部实例的引用是由编译器。


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?

解决方案

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.

这篇关于外部文件中的嵌套/内部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆