Java -- private constructor vs final and more

Roam picture Roam · Aug 30, 2013 · Viewed 7.5k times · Source

Suppose there is a class with all of its constructors declared as private.

Eg.:

public class This {
    private This () { }

    public someMethod( ){
    // something here
    }
   // some more-- no other constructors
}

From what I know, making all constructors private is similar to declaring the class "This" as final-- so that it can't be extended.

However, the Eclipse messages i'm getting are giving me the impression that this is possible-- an all-constructors-private class can be extended. Take a look at this:

When I attempt to extend this class with something like

public class That extends This {
    ...
}

Eclipse giving me an error that: "Implicit super constructor This() is not visible for default constructor. Must define an explicit constructor."

When i define a constructor of its own:

public class That extends This {
    That () {..} 
    ...
}

this time i'm getting : "Implicit super constructor This() is not visible for default constructor. Must explicitly invoke another constructor."

Is there a way to get around this-- of extending a class of which all constructors are private?

if yes, how?

if no, what's the difference between stopping a class from being extended by i.) making its constructors private, and ii.) defining it as final?

Note: i saw Can a constructor in Java be private? among some other discussions.

Answer

Sergey Kalinichenko picture Sergey Kalinichenko · Aug 30, 2013

You declare a class final vs. make its constructor private for different reasons:

  • You make class final to indicate that the class is not designed for inheritance.
  • You make all constructors private to give the class the control over its instantiation.

In other words, using final controls inheritance, while using private constructors control instantiation.

Note that declaring constructors private disables inheritance only from the outside. Inside the class, you may still inherit it with a named or an anonymous derived class.

When you make all constructors of the class private you need a static method that is public to make the class usable. One common kind of the static method is factory method: you can let the users of your class call private constructors indirectly through a public static method.