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?
We can't create public and private constructors simultaneously in a class, both without parameters. We can't instantiate the class with a private constructor. If we want to create an object of a class with private constructor then, we need to have public constructor along with it.
First, initiate a constructor as private. Then create a private static instance of this singleton class. Keep in mind to NOT instantiate it. Then, write a static method, which checks the static instance member for null and initiates the instance.
Yes, we can declare a constructor as private. If we declare a constructor as private we are not able to create an object of a class. We can use this private constructor in the Singleton Design Pattern.
If a constructor is declared as private, then its objects are only accessible from within the declared class. You cannot access its objects from outside the constructor class.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With