内部类中私有变量的范围? [英] Scope of private variables in an inner class?

查看:47
本文介绍了内部类中私有变量的范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;

    }
}

推荐答案

作用域在 Node{} 之间,但是它RedBlackTrees 下的任何代码都可以访问,前提是您提供明确的路径.

The scope is between the { and } of Node however it is accessible to any code under RedBlackTrees provided you give an explicit path.

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

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. For simplicity I would make the members "package local".

这篇关于内部类中私有变量的范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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