简体   繁体   English

在 Java 中使用私有默认构造函数子类化 class

[英]Subclassing a class with a private default constructor in Java

Say I have class A with a private constructor, and class B that extends it:假设我有带有私有构造函数的 class A和扩展它的 class B

public class A {
    private A() {}
}

public class B extends A {
    public B(){
        // error - there is no default constructor available in 'A'
    }
}

I know it is possible to call private constructors via Java Reflection, but how can I do it in the B constructor ?我知道可以通过 Java 反射调用私有构造函数,但是我该如何B构造函数中做到这一点? Thanks.谢谢。

If class B extends A and A 's constructor is private, subclassing is not possible unless both classes are defined in the same file as inner classes (see Preventing Instantiation of a Class ).如果 class B扩展A并且A的构造函数是私有的,则子类化是不可能的,除非两个类都在同一个文件中定义为内部类(请参阅防止 Class 的实例化)。 That's because the constructor of the subclass does an (either explicit or implicit) super() call.这是因为子类的构造函数进行了(显式或隐式) super()调用。 A super() call is basically just a call to the matching constructor and if that constructor is declared private , this call is not possible from some outer class (eg one defined in a different file). super()调用基本上只是对匹配构造函数的调用,如果该构造函数被声明为private ,则无法从某些外部 class(例如,在不同文件中定义的一个)调用此调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM