views:

61

answers:

4

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?

+1  A: 

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();
    }
}
Colin Hebert
The method `getInstance()` of class `Test` should be static. Otherwise it is not possible to make a call like `Test.getInstance()`.
vanje
@vanje, thanks, updated
Colin Hebert
A: 

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
mklhmnn
A: 

A class with only private constructors cannot be extended. It's as if it is final.

This is because each constructor has to invoke a superconstructor up the hierarchy.

The "way out" is to provide another non-private constructor, or make this one non-private.

(And a sidenote - class names in Java should (must) start with uppercase - i.e. Test rather than test)

Bozho
A: 

In addition to what "Colin Hebert" has said, it is a good practice to make any utility classes final.

dinidu