A class can be designed to prevent code outside the class declaration from creating instances of the class by declaring at least one constructor, to prevent the creation of a default constructor, and by declaring all constructors to be private (§6.6.1).
A public class can likewise prevent the creation of instances outside its package by declaring at least one constructor, to prevent creation of a default constructor with public access, and by declaring no constructor that is public or protected (§6.6.2).
Example 8.8.10-1. Preventing Instantiation via Constructor Accessibility
class ClassOnly {
private ClassOnly() { }
static String just = "only the lonely";
}
Here, the class ClassOnly cannot be instantiated, while in the following code:
package just;
public class PackageOnly {
PackageOnly() { }
String[] justDesserts = { "cheesecake", "ice cream" };
}
the public class PackageOnly can be instantiated only within the package just, in which it is declared. This restriction would also apply if the constructor of PackageOnly was protected, although in that case, it would be possible for code in other packages to instantiate subclasses of PackageOnly.