【问题标题】:Scope of private variables in an inner class?内部类中私有变量的范围?
【发布时间】:2014-08-03 10:33:41
【问题描述】:

在内部类中声明为私有的变量的范围是什么?例如,下面给出的代码中关键变量的范围是什么。

package redblacktrees;

public class RedBlackTrees<Key extends Comparable <Key>,Val> {

    private Node root;

    private class Node
    {
        private Key key;  //what is thescope of this variable
        private Val val;
        private Node left, right;

    }

    public Val get(Key key)
    {
        Node x = root;
        while(x != null)
        {
            int cmp = key.compareTo(x.key);
            if(cmp < 0)
                x = x.left;
            else if(cmp > 0)
                x = x.right;
            else
                return x.val;
        }

        return null;

    }
}

【问题讨论】:

    标签: java variables scope


    【解决方案1】:

    范围在Node{} 之间,但是只要您给出明确的路径,RedBlackTrees 下的任何代码都可以访问它。

    顺便说一句,当您以这种方式访问​​私有成员时,javac 编译器必须添加访问器方法,这些方法不会减慢代码的速度,但会产生令人困惑的堆栈跟踪。为简单起见,我会让成员“打包本地”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-18
      • 1970-01-01
      • 2011-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      相关资源
      最近更新 更多