In java, how do I make a class with a private constructor whose superclass also has a private constructor?

不想你离开。 提交于 2019-12-23 10:58:12

问题


As an example:

public class Foo {
    private Foo() {}
}

public class Bar extends Foo {
    private Bar() {}

    static public doSomething() {
    }
}

That's a compilation error right there. A class needs to, at least, implicitly call its superclass's default constructor, which in this case is isn't visible in Foo.

Can I call Object's constructor from Bar instead?


回答1:


You can't. You need to make Foo's constructor package private at the very least (Though I'd probably just make it protected.

(Edit - Comments in this post make a good point)




回答2:


This is actually a symptom of a bad form of inheritance, called implementation inheritance. Either the original class wasn't designed to be inherited, and thus chose to use a private constructor, or that the entire API is poorly designed.

The fix for this isn't to figure out a way to inherit, but to see if you can compose the object instead of inheriting, and do so via interfaces. I.e., class Foo is now interface Foo, with a FooImpl. Then interface bar can extend Foo, with a BarImpl, which has no relation to FooImpl.

Inside BarImpl, you could if you wish to do some code reuse, have a FooImpl inside as a member, but that's entirely up to the implementation, and will not be exposed.




回答3:


You won't be able to create an instance of Bar for as long as Foo has a private constructor. The only way you would be able to do it is if Foo had a protected constructor.




回答4:


You can't call Object's constructor directly from Bar while it's a subclass of Foo, it would have to through Foo's constructor, which is private in this case.

When you declare Foo's constructor private, it does not create a default public constructor. Since Bar has to invoke Foo's constructor, it is not possible to leave it private. I would suggest, as others have, on using protected instead of private.



来源:https://stackoverflow.com/questions/462094/in-java-how-do-i-make-a-class-with-a-private-constructor-whose-superclass-also

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!