Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

class — class declaration

class — class declaration: The class keyword starts a class declaration, a named reference type with fields, methods, constructors, initializers, and member types.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

class

The class keyword starts a class declaration, a named reference type with fields, methods, constructors, initializers, and member types.

Use class to model objects with state and behavior; extends selects one superclass, while implements can name multiple interfaces.

A public top-level class requires a same-named source file; a default constructor is supplied only when no constructor is declared.

A static nested class has no outer instance, whereas a non-static member inner class has an enclosing instance. A local or anonymous class declared in a static context may have no immediately enclosing instance.

The nested Counter class owns state: reflection prints Counter, and increment changes its value from 4 to 5.

Examples

public class Main {
    static class Counter {
        private int value;
        Counter(int initial) { value = initial; }
        int increment() { return ++value; }
    }

    public static void main(String[] args) {
        Counter counter = new Counter(4);
        System.out.println(counter.getClass().getSimpleName());
        System.out.println(counter.increment());
    }
}

Result

Counter
5

The nested Counter class owns state: reflection prints Counter, and increment changes its value from 4 to 5.

Sources