Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 640
Hans Sjunnesson Avatar asked Jan 20 '09 16:01

Hans Sjunnesson


People also ask

Can you have both public & private constructors in the same class?

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.

How can you make a class if the constructor is private?

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.

Is it possible to have a private constructor write a class and try it out if possible How do you create an instance of it from another class?

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.

What will happen if the two constructors are declared as private?

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.


2 Answers

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)

like image 69
Richard Walton Avatar answered Nov 11 '22 04:11

Richard Walton


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.

like image 29
Chii Avatar answered Nov 11 '22 05:11

Chii