[英]Why am I able to inherit & call a private constructor in a subclass?
I read that it is not possible to create a subclass from a class whose constructor is private but weirdly I am able to do it, is there something more to this snippet? 我读到,从构造函数是私有的类创建子类是不可能的,但奇怪的是我能够做到这一点,这个代码片段还有更多内容吗?
Please someone provide an easy to understand & satisfactory explanation. 请有人提供易于理解和满意的解释。
public class app {
public static void main(String[] args) {
app ref = new app();
myInheritedClass myVal = ref.new myInheritedClass(10);
myVal.show();
}
int myValue = 100;
class myClass {
int data;
private myClass(int data) {
this.data = data;
}
}
class myInheritedClass extends myClass {
public myInheritedClass(int data) {
super(data);
}
public void show() {
System.out.println(data);
}
}
}
I ran this snippet on https://www.compilejava.net/ and the output was 10. 我在https://www.compilejava.net/上运行了这个片段,输出为10。
Because your classes are both nested classes (in your case, specifically inner classes), which means they're both part of the containing class, and so have access to all private things in that containing class, including each other's private bits. 因为您的类都是嵌套类 (在您的情况下,特别是内部类),这意味着它们都是包含类的一部分,因此可以访问包含类的所有私有事物,包括彼此的私有位。
If they weren't nested classes, you wouldn't be able to access the superclass's private constructor in the subclass. 如果它们不是嵌套类,则无法访问子类中的超类私有构造函数。
More about nested classes in the nested class tutorial on the Oracle Java site. 有关Oracle Java站点上嵌套类教程中嵌套类的更多信息。
This compiles, because A
and B
are inner classes, which are nested classes ( live copy ): 这个编译,因为
A
和B
是内部类,它们是嵌套类( 实时副本 ):
class Example
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println("Ran at " + new java.util.Date());
}
class A {
private A() {
}
}
class B extends A {
private B() {
super();
}
}
}
This compiles, because A
and B
are static nested classes ( live copy ): 这个编译,因为
A
和B
是静态嵌套类( 实时拷贝 ):
class Example
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println("Ran at " + new java.util.Date());
}
static class A {
private A() {
}
}
static class B extends A {
private B() {
super();
}
}
}
This does not compile because A
's constructor is private; 这不会编译,因为
A
的构造函数是私有的; B
cannot access it (I don't really need Example
in this case, but I've included it in the two above, so for context...) ( live copy ): B
无法访问它(在这种情况下我真的不需要Example
,但我已将它包含在上面的两个中,因此对于上下文...)( 实时复制 ):
class Example
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println("Ran at " + new java.util.Date());
}
}
class A {
private A() {
}
}
class B extends A {
private B() {
super(); // COMPILATION FAILS HERE
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.