Conceptcore
Nested and inner classes
Also called nested class, inner class, static nested class, member class, local class, anonymous class, nested type, enclosing instance, Outer.this.
A nested class is declared inside another class. A static nested class is only grouped by name, and an inner class also holds a reference to an object of the outer class.
- Applies to
- core-languages
Idea
A nested class is a class declared inside another class. The name of the inner one is then a member of the outer one, such as Playlist.Cursor, and the nested class can use the private members of the outer class. Languages differ on one question: does an object of the nested class belong to an object of the outer class?
- A static nested class does not. It is a class like any other, grouped under the name of the outer class. The Java tutorial says: "Nested classes that are declared static are called static nested classes."1
- An inner class does. Each inner object holds a hidden reference to one outer object, and its methods can read the fields of that object as if they were its own. "Non-static nested classes are called inner classes."
Java has both, and two more kinds that are declared in a method body: a local class, which has a name, and an anonymous class, which is declared and made in one expression. In Java:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Main {
static class Playlist {
private final String name;
private final List<String> songs = new ArrayList<>();
Playlist(String name) {
this.name = name;
}
// A static nested class: no Playlist instance; it gets data through parameters.
static class Stats {
final int count;
Stats(Playlist p) {
count = p.songs.size(); // may read the private field through a reference
}
}
// An inner class: each Cursor belongs to one Playlist and reads its fields.
class Cursor implements Iterator<String> {
private int next = 0;
public boolean hasNext() {
return next < songs.size(); // songs is Playlist.this.songs
}
public String next() {
return name + ": " + songs.get(next++);
}
}
void add(String song) {
songs.add(song);
}
}
public static void main(String[] args) {
Playlist p = new Playlist("road");
p.add("one");
p.add("two");
Playlist.Stats s = new Playlist.Stats(p); // made without an outer instance
Playlist.Cursor c = p.new Cursor(); // made from an outer instance
System.out.println(s.count);
while (c.hasNext()) {
System.out.println(c.next());
}
String prefix = "> "; // effectively final, so the class below can use it
// An anonymous class: declared and instantiated in one expression.
Iterator<String> loud = new Iterator<>() {
private final Iterator<String> in = p.new Cursor();
public boolean hasNext() {
return in.hasNext();
}
public String next() {
return prefix + in.next().toUpperCase();
}
};
while (loud.hasNext()) {
System.out.println(loud.next());
}
}
}
2
road: one
road: two
> ROAD: ONE
> ROAD: TWO
Stats is a static nested class: new Playlist.Stats(p) needs no Playlist object, and the constructor gets the playlist as a parameter. Cursor is an inner class: p.new Cursor() makes a cursor that belongs to p, and its methods read songs and name of that playlist. The anonymous class at the end implements Iterator in place and uses the local variable prefix.
How it works
- The outer reference. An inner object has a hidden field that points to the outer object. The JLS calls it the immediately enclosing instance, and it "is determined when the object is created".2 Inside the inner class, the name
songsmeansPlaylist.this.songs. A static nested class has no such field: "Just as a static method of a class has no current instance of the class in its body, a static nested class has no immediately enclosing instance in its body." - Making an inner object. An inner object needs an outer object. In an instance method of
Playlist,new Cursor()usesthis. Elsewhere, Java code writesp.new Cursor(), and Kotlin code writesp.Cursor(). - Access to private members. A nested class is a member of the outer class, so it can use the private members of the outer class, and the outer class can use the private members of the nested class. C# says that a nested type "can access private and protected members of the containing type, including any inherited protected members".3
- Captured locals. A local class, an anonymous class or a lambda in Java can use a local variable of the method only if the variable is final or effectively final. The object gets a copy of the value, so the rule keeps the copy and the variable equal.
- The compiled form. The JVM has no nested classes. The compiler makes a separate class file for each one, such as
Main$Playlist$Cursor.class, and for an inner class it adds the outer reference as a constructor parameter and a field.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Idiom | |
| C++ | Native | |
| Java | Native | |
| C | Absent | A struct declared inside a struct is not scoped to it, and C has no member functions to nest. |
| C# | Native | |
| JavaScript | Idiom | |
| TypeScript | Idiom | As JavaScript; a namespace with the same name as a class can hold types, which gives names such as Playlist.Cursor; no example file because it would repeat the JavaScript one. |
| Go | Idiom | |
| Rust | Idiom | |
| Kotlin | Native | A class inside a class is nested and has no outer object, inner class adds one, and an object expression makes an anonymous object; no example file because kotlinc is not installed on the machine that recorded the examples. |
| SQL | Does not apply | SQL has no classes. |
| Bash | Does not apply | Bash has no classes. |
| PowerShell | Absent | PowerShell classes cannot contain class definitions; code declares each class at the top level of a script or module. |
| HTML | Does not apply | HTML has no classes in this sense; the class attribute names CSS selectors. |
| CSS | Does not apply | CSS has no classes in this sense; a class selector matches elements. |
| Regular expressions | Does not apply | A pattern has no classes. |
| Language | Verdict | Mechanism |
|---|---|---|
| Java | native | static nested, inner member, local and anonymous classes; Outer.this; outer.new Inner() |
| Kotlin | native | nested classes by default; inner class for an outer reference; object : expressions |
| C# | native | nested types with no outer instance; private by default |
| C++ | native | nested classes with no outer this; local classes in functions |
| Python | idiom | a class statement in a class body makes a class attribute; no outer instance |
| JavaScript | idiom | a class expression in a static field; a class in a function closes over its variables |
| TypeScript | idiom | as JavaScript; namespaces merged with a class for nested type names |
| Go | idiom | separate types in the package; local types without methods; closures |
| Rust | idiom | modules group types; local items in functions; closures |
| C | absent | a struct inside a struct does not make a nested scope for its name |
| Bash | n/a | no classes |
| PowerShell | absent | classes cannot be nested |
| SQL | n/a | no classes |
| Regex | n/a | no classes |
| HTML | n/a | no classes |
| CSS | n/a | no classes |
- Kotlin reverses the Java default. A class inside a class is nested and has no outer object; the keyword
inneradds one: "A nested class marked as inner can access the members of its outer class. Inner classes carry a reference to an object of an outer class".4 - C# nested types are like Java static nested classes. "Regardless of whether the outer type is a class, interface, or struct, nested types default to private."3 For the outer object, C# code does by hand what a Java inner class does: "To access the containing type, pass it as an argument to the constructor of the nested type."
- C++ nested classes have access to the private names of the outer class, but no outer object: "it is otherwise independent and has no special access to the this pointer of the enclosing class".5
class Playlist:
LIMIT = 3
class Cursor: # a class attribute of Playlist; no outer instance
def __init__(self, owner):
self.owner = owner
self.i = 0
def __iter__(self):
return self
def __next__(self):
if self.i >= len(self.owner.songs):
raise StopIteration
self.i += 1
return f"{self.owner.name}: {self.owner.songs[self.i - 1]}"
def limit(self):
return Playlist.LIMIT # LIMIT alone would be a NameError here
def __init__(self, name):
self.name = name
self.songs = []
def __iter__(self):
return Playlist.Cursor(self)
p = Playlist("road")
p.songs += ["one", "two"]
print(list(p), Playlist.Cursor(p).limit())
['road: one', 'road: two'] 3
- Verdict: idiom. A class statement inside a class body makes a class attribute,
Playlist.Cursor. It has no link to an instance ofPlaylist, so the code passesownerby hand, as in C# and C++. - The body of a nested class or a method does not see the names of the outer class body.
limitmust writePlaylist.LIMIT; the nameLIMITalone is not found.
#include <iostream>
#include <string>
#include <vector>
class Playlist {
public:
explicit Playlist(std::string name) : name_(std::move(name)) {}
void add(std::string song) { songs_.push_back(std::move(song)); }
class Cursor { // a nested class; it has no this of Playlist
public:
explicit Cursor(const Playlist &owner) : owner_(&owner) {}
bool next() { return ++i_ < owner_->songs_.size(); } // private member: allowed
std::string current() const { return owner_->name_ + ": " + owner_->songs_[i_]; }
private:
const Playlist *owner_;
std::size_t i_ = static_cast<std::size_t>(-1);
};
Cursor cursor() const { return Cursor(*this); }
private:
std::string name_;
std::vector<std::string> songs_;
};
int main() {
Playlist p("road");
p.add("one");
p.add("two");
Playlist::Cursor c = p.cursor();
while (c.next()) {
std::cout << c.current() << "\n";
}
}
road: one
road: two
- Verdict: native. A C++ nested class is a member of the outer class, so it can use the private members of
Playlist, but it has nothisof an outer object. It keeps a pointer, which the code sets in the constructor. - The pointer can outlive the
Playlist. Ifpis destroyed whilecis still in use,creads freed memory; a Java inner object would keep its outer object alive instead.
import java.util.function.IntSupplier;
public class Main {
static class Counter {
private int value = 10;
class Step {
private int value = 1; // hides Counter.value inside Step
void apply() {
Counter.this.value += value; // Counter.this names the outer instance
}
}
IntSupplier reader(int scale) {
// A local class: declared in a method; it can use the effectively final parameter scale.
class Reader implements IntSupplier {
public int getAsInt() {
return value * scale;
}
}
return new Reader();
}
}
public static void main(String[] args) {
Counter c = new Counter();
Counter.Step step = c.new Step();
step.apply();
step.apply();
IntSupplier r = c.reader(3);
System.out.println(c.value + " " + r.getAsInt());
IntSupplier lambda = () -> c.value * 2; // a lambda replaces most one-method anonymous classes
System.out.println(lambda.getAsInt());
}
}
12 36
24
- Verdict: native. Java has all four kinds: static nested classes, inner member classes, local classes and anonymous classes.
- In
Step, the namevaluemeans the field ofStep.Counter.this.valuereaches the field of the outer object, which the inner object holds a hidden reference to. - A local class or a lambda can use a local variable or a parameter of the method only if it is final or effectively final: it gets a copy of the value, not the variable.
using System;
using System.Collections.Generic;
var p = new Playlist("road");
p.Add("one");
p.Add("two");
var c = new Playlist.Cursor(p); // the outer object is passed by hand
while (c.MoveNext())
{
Console.WriteLine(c.Current);
}
Console.WriteLine(Playlist.Describe(p));
class Playlist
{
private readonly string name;
private readonly List<string> songs = [];
public Playlist(string name) => this.name = name;
public void Add(string song) => songs.Add(song);
public static string Describe(Playlist p) => new Stats(p).ToString();
// A public nested type. It has no outer instance; it gets one in its constructor.
public class Cursor(Playlist owner)
{
private int next = -1;
public bool MoveNext() => ++next < owner.songs.Count; // private members are visible
public string Current => $"{owner.name}: {owner.songs[next]}";
}
// A private nested type: code outside Playlist cannot name it.
private record Stats(Playlist P)
{
public override string ToString() => $"{P.songs.Count} songs";
}
}
road: one
road: two
2 songs
- Verdict: native. A C# nested type is like a Java static nested class: it has no hidden reference to an outer object. Code that needs one passes it, here as a primary constructor parameter.
- A nested type sees the private members of the type that contains it, so
Cursorreadsowner.songs. Nested types are private unless they say otherwise, soStatsis hidden from the top-level statements.
class Playlist {
static Cursor = class { // a class stored in a static field: a nested class by convention
#owner;
#i = 0;
constructor(owner) {
this.#owner = owner;
}
next() {
const songs = this.#owner.songs;
return this.#i < songs.length
? { done: false, value: `${this.#owner.name}: ${songs[this.#i++]}` }
: { done: true, value: undefined };
}
};
constructor(name) {
this.name = name;
this.songs = [];
}
[Symbol.iterator]() {
return new Playlist.Cursor(this);
}
}
function makeCounter(start) {
// A class declared in a function closes over the function's variables.
class Counter {
next() {
return start++;
}
}
return new Counter();
}
const p = new Playlist("road");
p.songs.push("one", "two");
console.log([...p]);
const c = makeCounter(5);
console.log(c.next(), c.next());
[ 'road: one', 'road: two' ]
5 6
- Verdict: idiom. JavaScript has no nested class declarations. A class expression stored in a static field,
Playlist.Cursor, gives the same name structure, and the code passes the outer object by hand. - A class declared inside a function is a closure: its methods can read and change the function's local variables, here
start. This plays the part of a Java local class, without the rule that the variable must not change.
package main
import "fmt"
type Playlist struct {
name string
songs []string
}
// cursor is a separate type of the package. Its name and its field link it to Playlist.
type cursor struct {
owner *Playlist
i int
}
func (c *cursor) Next() (string, bool) {
if c.i >= len(c.owner.songs) {
return "", false
}
c.i++
return c.owner.name + ": " + c.owner.songs[c.i-1], true
}
func (p *Playlist) Cursor() *cursor { return &cursor{owner: p} }
func main() {
p := &Playlist{name: "road", songs: []string{"one", "two"}}
c := p.Cursor()
for s, ok := c.Next(); ok; s, ok = c.Next() {
fmt.Println(s)
}
// A type declared in a function is local to it. It cannot have methods,
// so a closure does the job of a local or anonymous class.
type pair struct{ a, b string }
x := pair{"one", "two"}
n := 0
next := func() int { // an anonymous function that keeps n between calls
n++
return n
}
fmt.Println(x, next(), next())
}
road: one
road: two
{one two} 1 2
- Verdict: idiom. Go has no nested types and no inner classes. A second type in the same package, with a lower-case name, does the job of a private nested class; code in the package can still use it.
- A type declared in a function cannot have methods, so Go code uses a closure where Java uses an anonymous class.
mod playlist {
pub struct Playlist {
name: String,
songs: Vec<String>,
}
// A struct in the same module: it can read the private fields of Playlist.
pub struct Cursor<'a> {
owner: &'a Playlist,
i: usize,
}
impl Playlist {
pub fn new(name: &str, songs: &[&str]) -> Playlist {
Playlist { name: name.to_string(), songs: songs.iter().map(|s| s.to_string()).collect() }
}
pub fn cursor(&self) -> Cursor<'_> {
Cursor { owner: self, i: 0 }
}
}
impl<'a> Iterator for Cursor<'a> {
type Item = String;
fn next(&mut self) -> Option<String> {
let song = self.owner.songs.get(self.i)?;
self.i += 1;
Some(format!("{}: {}", self.owner.name, song))
}
}
}
fn main() {
let p = playlist::Playlist::new("road", &["one", "two"]);
for line in p.cursor() {
println!("{line}");
}
struct Pair(u32, u32); // a local item: visible only in main
let scale = 10;
let add = |p: Pair| (p.0 + p.1) * scale; // a closure captures scale; an item could not
println!("{}", add(Pair(1, 2)));
}
road: one
road: two
30
- Verdict: idiom. Rust has no nested types inside a struct or an
impl. A module groups the two types, and privacy is per module, soCursorreads the private fields ofPlaylist. - The lifetime
'aties the cursor to the playlist: the compiler refuses code that dropspwhile a cursor is in use. A struct declared in a function is local to it but cannot use the function's variables; a closure can.
Variations and related ideas
- Anonymous classes and lambdas. An anonymous class that implements an interface with one method can be a lambda in Java, Kotlin and C#, which is shorter. An anonymous class is still useful when the object needs fields or more than one method. Kotlin uses an object expression,
object : MouseAdapter() { ... }. - Local classes and closures. A local class is declared in a method and can use its variables. In JavaScript, Python, Go and Rust, a closure does the same job, and a class declared in a JavaScript function is itself a closure.
- Nested types for grouping. A nested type gives a name such as
Map.EntryorPlaylist.Cursor, which shows that the type exists for its outer type. The Java tutorial gives this reason: "It is a way of logically grouping classes that are only used in one place".1 Go and Rust use the module or package for grouping instead. - Builders and iterators. The usual nested classes are a static nested
Builderthat makes the outer object, and an inner iterator or cursor that walks over the outer object's data.
Pitfalls
- An inner object keeps its outer object alive. The hidden reference stops the garbage collector from freeing the outer object while the inner object is reachable. A listener or a callback made as an inner or anonymous class keeps a large outer object in memory. Make a nested class static unless it needs the outer object.
- Serialization. "Serialization of inner classes, including local and anonymous classes, is strongly discouraged."1 The serialized form contains the hidden outer field and names that the compiler makes, and these can differ between compilers.
- Shadowed names. A field of the inner class with the same name as a field of the outer class hides it. Write
Outer.this.namein Java orthis@Outer.namein Kotlin for the outer one. - A dangling outer pointer in C++. A C++ nested object that keeps a pointer or a reference to its outer object does not keep that object alive. If the outer object is destroyed first, the pointer is invalid.
- The outer class body is not a scope in Python. A method of a nested class cannot see the names of the outer class body; it must write
Playlist.LIMIT. The nested class also has no outer object; code must pass one. - Effectively final in Java. A local variable that a local class, an anonymous class or a lambda uses cannot change after its assignment. Code that must change a counter from inside uses a field, an array of one element or an
AtomicInteger.
Cost
A static nested class costs the same as a top-level class. An inner object has one more field, the outer reference, so it uses one pointer more of memory and its constructor has one more parameter. Each nested, local or anonymous class is a separate class for the runtime, which must load it before its first use. Access from an inner class to a private member of the outer class is a field access; older Java compilers made extra accessor methods for it.
History
Simula 67 and its successor BETA let a class contain other classes: "BETA language introduced this notion of nested classes."6 "Inner classes became a feature of the Java programming language starting with version 1.1", in 1997, together with local and anonymous classes. Their first big use was event handling: "Local inner classes are often used in Java to define callbacks for GUI code." The JLS defines the kinds today: "An inner class is a nested class that is not explicitly or implicitly static."2 C++ and C# chose nested classes without an outer object, and Kotlin made that the default and added the inner keyword. Java 8 added lambdas, which replaced most anonymous classes with one method.
References
- Nested Classes, The Java Tutorials, Nested Classes; Inner Classes; Serialization
- Chapter 8, Classes, The Java Language Specification, Java SE 25 Edition, 8.1.1.4 static Classes; 8.1.3 Inner Classes and Enclosing Instances
- Nested types, C# programming guide, Introduction
- Nested and inner classes, Kotlin documentation, Inner classes
- Nested classes, cppreference.com, Explanation
- Inner class, Wikipedia, Programming languages; GUI code
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag F0YZKX Edit this page History Report an error Markdown