内部类中私有变量的范围 [英] Scope of private variables within inner classes
问题描述
考虑以下代码:
public class Foo
{
class Bar
{
private String barbar;
public Bar( String b ) { barbar = b; }
}
class Meh
{
Bar b = new Bar("BAR!");
public void displayName() {
System.out.println( b.barbar );
}
}
}
Java允许类 Meh
访问私有实例变量 barbar
,该变量在 Bar
private >.
Java allows class Meh
to access the private instance variable, barbar
, which is declared as private
within Bar
.
我知道在>此处之前已问过此问题..但是,答案只是基本上重申了观察到的范围是什么(在 Foo
类的大括号内可以访问 barbar
),但没有提供任何解释.经过一番谷歌搜索后,我无法对这种行为进行深入的讨论.我想知道的是,这种范围界定行为是否有特定的理由.我本来希望 barbar
在类 Bar
的括号内是私有的.
I know this question has been asked before here. However, the answer just basically reiterates that the observed scope is what it is (that barbar
is accessible within the braces of class Foo
), but offers no explanation. After some Googling, I hadn't been able to land on a good discussion of this behavior. What I would like to know is if there's a specific rationale for this scoping behavior. I would have expected barbar
to be private "within the braces" of class Bar
.
推荐答案
The fundamental aspect of this is that inner classes (as opposed to static nested classes) are part of their enclosing class. They aren't separate from it, or from each other. So just like other parts of the enclosing class (constructors and methods) have access to all of its private information, so do all the members of the inner classes. Inner classes are, in some sense, a bit of a fiction that we use as a convenient abstraction mechanism. And since inner classes are part of the enclosing class, their private information is its private information, and so is shared with other inner classes.
这篇关于内部类中私有变量的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!