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.
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.
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 class PackageOnly can be instantiated only within the package just, in which it is declared.