简体   繁体   English

内部类中私有变量的范围?

[英]Scope of private variables in an inner class?

What is the scope of variables that are declared as private in an inner class? 在内部类中声明为私有的变量的范围是什么? For example what would be the scope of key variable in th code given below. 例如,下面给出的代码中键变量的范围是什么。

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;

    }
}

The scope is between the { and } of Node however it is accessible to any code under RedBlackTrees provided you give an explicit path. 范围在Node{}之间,但是只要您提供明确的路径, RedBlackTrees下的任何代码都可以访问它。

BTW When you access private members this way, the javac compiler has to add accessor methods which don't slow down the code that much but can give confusing stack traces. 顺便说一句,当您以这种方式访问​​私有成员时, javac编译器必须添加访问器方法,该方法不会使代码减慢太多,但会产生令人困惑的堆栈跟踪。 For simplicity I would make the members "package local". 为简单起见,我将成员设置为“本地包”。

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

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