【发布时间】:2017-02-20 10:55:17
【问题描述】:
在我的数据结构类中,我们使用私有内部类来实现红/黑树的Nodes。这种Node是红/黑树独有的,所以内部类的可见性是private。内部类的成员是always accessible from the enclosing class。
我应该如何为这个内部类的成员选择可见性?如果编译器没有区别,哪种可见性在语义上最有意义?
public class RedBlackTree<K extends Comparable<? super K>, V> {
private static enum NodeColor { RED, BLACK }
private class Node {
private final K key; // these are private, currently for no particular reason
private V value;
private Node left;
private Node right;
private NodeColor color;
private Node(K key, V value, NodeColor color) {
this.key = key;
this.value = value;
this.color = color;
}
}
// Precondition - both children are red, and node is black.
// Postcondition - both children are black, and node is red.
private void colorFlip(Node node) {
node.color = NodeColor.RED;
node.left.color = NodeColor.BLACK; // these statements compile, as expected
node.right.color = NodeColor.BLACK;
}
}
在this question 中,OP 说private 在语义上是有意义的,而在this answer 中,作者说public 在语义上是有意义的。如果有的话,哪一个是最佳做法?
【问题讨论】:
标签: java visibility inner-classes