---
spec: JLS
title: "The Java Language Specification"
edition: "Java SE 13 Edition"
java_version: 13
chapter: "Chapter 8. Classes"
section: "8.8.10"
heading: "8.8.10. Preventing Instantiation of a Class"
parent: "8.8. Constructor Declarations"
source: https://docs.oracle.com/javase/specs/jls/se13/html/jls-8.html#jls-8.8.10
id: "8.8.10"
url: https://jvm.obfuscated.software/jls/se13/8.8.10.html
raw: https://jvm.obfuscated.software/jls/se13/8.8.10.md
---

# 8.8.10. 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 a default constructor, and by declaring all constructors to be `private` ([§6.6.1](6.6.1.md)).

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](6.6.2.md)).

**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`.
