繁体   English   中英

有没有办法从Java的派生类访问嵌套在超类中的私有内部类?

[英]Is there any way to access a private inner class that is nested in a super class from a derived class in Java?

也许我没有正确说出这个问题。 这是我作为示例的代码:

//a generic binary tree class
public class BinaryTree<T extends Comparable<T>> {

  //inner node class
  private final static class Node<T>{

    //code
  }

   private Node<T> root; //instance variable for this class


   //methods
        //assume setters/getters for the root
}

//MyTree class. I am extending it because I want to use all of the
//methods in the BinaryTree class and then some more methods that apply
//only to this class

 class MyTree extends BinaryTree<Student> {

       void aMethod(){

             //I want to be able to do this but I get errors about trying to access a private class
             Node<Student> node = root;

       }

   public static void main(String[] args) {


   }

  }

  class Student implements Comparable<Student> { //implemented method here }

在上面的示例中,我希望能够访问MyTree类中的根。 我怎样才能做到这一点? 也许有更好的方法进行设置? 我认为最好摘除内部Node类并使其成为自己的类?

//inner node class
private final static class Node<T>{
   //code
}

public Node<T> root; //instance variable for this class

root不是内部类的成员,它是公共的,因此您已经可以从任何类(不仅仅是BinaryTree子类)访问它。 您确定变量应该是公共的并且是可变的吗?

但是要回答您的问题,内部类Node必须是公共的或受保护的,以便可以从子类访问它。 将其更改为以下任何一项都可以。 protected保护者是最佳选择。

public final static class Node<T>{
protected final static class Node<T>{
final static class Node<T>{

请注意,第三个选项仅适用于子类与父类位于同一包中的情况。

当您将嵌套类设为private ,这意味着该类是主类的实现详细信息的一部分。 也就是说,您的主类具有它需要提供的公共方法,为了提供这些公共方法,程序员决定定义另一个类以帮助实现(例如,保存某种类型的数据表,公共方法使用)。 (有时这意味着该类变得太大,太复杂,并且需要进行一些重构。但这是另一个问题的问题。)

在任何情况下,如果你想要类,使用BinaryTree<T>以便能够使用Node<T>这是一个迹象表明, Node<T>是的宗旨的重要组成部分BinaryTree类(因为它似乎客户端) ,而不仅仅是实现细节。 这意味着它可能不应该是private

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM