首页 > 代码库 > 有关java中私有成员能否被继承的问题
有关java中私有成员能否被继承的问题
写程序中,无意中想到这个问题,随手搜了一下,发现大家对这个问题的看法不一
先看一下官方文档
http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
What You Can Do in a Subclass
A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-private members of the parent. You can use the inherited members as is, replace them, hide them, or supplement them with new members:
Private Members in a Superclass
A subclass does not inherit the private
members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass.
A nested class has access to all the private members of its enclosing class—both fields and methods. Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the private members of the superclass
从上面可以看出子类是可以继承父类的public和protected的成员的,如果父类和子类在同一个包里,那么也可以继承父类的package-private成员(thinking in java中的翻译是友好的、而budi的java7 程序设计中的翻译是默认的)。但是子类不能继承父类的private成员。但是可以通过public和protected方法访问得到私有成员。
正方不能继承的:
《通过实验看 Java 中私有成员是否能被继承》续
http://blog.csdn.net/holy_phoenix/article/details/488864
反方:可以继承
Java类中的私有成员的继承机制.pdf
可以看下篇文章。其他的都只是口头说明,没有实验支撑
我的观点是不可以继承,我看上面的文章,我认为作者在内存中看到的父类的成员,因为子类如果想实例化,之前要有父类的对象。而作者是把这个作为子类的对象