extends of the class with private constructor

JavaConstructor

Java Problem Overview


Suppose we have the following code:

class Test {
	private Test() {
		System.out.println("test");
	}

}

public class One extends Test {

	One() {
		System.out.println("One");
	}

	public static void main(String args[]) {

		new One();
	}
}

When we create an object One, that was originally called the parent class constructor Test(). but as Test() was private - we get an error. How much is a good example and a way out of this situation?

Java Solutions


Solution 1 - Java

There is no way out. You have to create an available (protected, public or default) super constructor to be able to extend test.

This kind of notation is usually used in utility classes or singletons, where you don't want the user to create himself an instance of your class, either by extending it and instanciating the subclass, or by simply calling a constructor of your class.

When you have a class with only private constructors, you can also change the class to final because it can't be extended at all.


Another solution would be having a method in test which create instances of test and delegate every method call from One to a test instance. This way you don't have to extend test.

class Test {
    private Test() {
        System.out.println("test");
    }
    public static Test getInstance(){
        return new Test();
    }
    public void methodA(){
        //Some kind of implementation
    }
}

public class One {
    private final Test test;
    One() {
        System.out.println("One");
        test = Test.getInstance();
    }

    public void methodA(){
        test.methodA();
    }

    public static void main(String args[]) {
        new One();
    }
}

Solution 2 - Java

Make the constructor of test non-private or move One into test.

BTW, your sample code contains a few issues:

  • classes should be named title case (Test instead of test)
  • I'd suggest to make the One's constructor private unless it is called from a different class in the same package

Solution 3 - Java

Actually, I found there is a way out. Like this:

class Base {
    private Base() {

    }

    public void fn() {
        System.out.println("Base");
    }

    public static class Child extends Base {
        public void fn() {
            System.out.println("Child");
        }
    }

    public static Base getChild() {
        return new Child();
    }
}

Now, you can use getChild() to get instance of the extended class.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser471011View Question on Stackoverflow
Solution 1 - JavaColin HebertView Answer on Stackoverflow
Solution 2 - JavaMotView Answer on Stackoverflow
Solution 3 - JavadelphifirstView Answer on Stackoverflow