Java内部类 [英] Inner Class in Java
问题描述
我正在阅读有关学习Java"的内部类的文章.我找到了这段代码
I was reading about Inner class in Learning Java. I found this code
class Animal{
class Brain{
}
}
编译后,javap 'Animal$Brain'
给出的输出为
Compiled from "Animal.java"class
Animal$Brain {
final Animal this$0;
Animal$Brain(Animal);
}
解释了内部类如何在内部类构造函数中获取对其封闭实例的引用.但是当我这样定义内部类为私有类
which explains how the inner class gets the reference to its enclosing instance in the inner class constructor. But when I define the inner class as private like this
class Animal{
private class Brain{
}
}
然后在编译后,javap 'Animal$Brain'
给出的输出为
then after compiling, javap 'Animal$Brain'
gives the output as
Compiled from "Animal.java"
class Animal$Brain {
final Animal this$0;
}
那么输出为何不同? 为什么未显示内部类构造函数? 在后一种情况下,内部类也将获取封闭类实例的引用.
So why is the output different? Why is the inner class constructor not shown? In the latter case also, the inner class is getting the reference of enclosing class instance.
推荐答案
好问题.根据此,
如果不使用任何选项,则javap会打印出传递给它的类的包,受保护的字段和方法的公共字段和方法
由于已将Brain
声明为私有内部类,因此其默认构造函数将隐式变为私有,因此在Animal
类外部将不可见.
Since you have declared Brain
as a private inner class, its default constructor will be implicitly made private and hence it will not be visible outside the Animal
class.
参考: http: //docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.8.9
这篇关于Java内部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!