8.6.8 Preventing Instantiation of a Class

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 an implicit constructor, and 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 declaring no constructor that is public.

Thus, in the example:


class ClassOnly {
	private ClassOnly() { }
	static String just = "only the lonely";
}

the class ClassOnly cannot be instantiated, while in the example:


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.

Bow, bow, ye lower middle classes!
Bow, bow, ye tradesmen, bow, ye masses!
Blow the trumpets, bang the brasses!
Tantantara! Tzing! Boom!
—W.S. Gilbert, Iolanthe