Since a constructor (although private) has been defined in the superclass, the base class cannot access it, hence even though the base class has a default constructor, it cannot make an implicit call to the constructor in the superclass (since it is private). Any constructor must have a call to a constructor in the supercalss as its first statement. So effectively what we are doing is trying to access the private member of the superclass which is illegal in the first place. The class by itself can be instantiated with a private constructor, there are no problems.
When the compiler's not happy, ain't nobody happy.
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32611
4
posted
0
Yes, you can have a private constructor. It is used for two main reasons:
To prevent the class being instantiated at all.
To restrict the class from being instantiated outside a factory method. Do a search for singleton pattern, which uses that trick.
If you have a class which only has private constructors, it is impossible to inherit from that class, so you ought to mark the class "final" as well.