Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

class

Declares a class — a description of objects: their fields and methods.

Available since: Java 1.0

Syntax

class Name { fields; constructors; methods }

Examples

A class with fields, a constructor and a method:

class BankAccount {
    private final String owner;
    private double balance;
 
    BankAccount(String owner) {
        this.owner = owner;
    }
 
    void deposit(double amount) {
        balance += amount;
    }
 
    String info() {
        return owner + ": " + balance;
    }
}
 
void main() {
    var account = new BankAccount("Anna");
    account.deposit(50);
    account.deposit(25.5);
    IO.println(account.info());
}

Output:

Anna: 75.5

Notes

In a regular project each public class lives in its own file with the same name: BankAccount.java. In a compact source file with void main() (Java 25) classes can be declared next to main.

If a class only holds data, a record is shorter.

See also

  • new — Creates a new object or array and calls the constructor.
  • this — A reference to the current object — the one whose method or constructor is running.
  • record — Declares a record — an immutable data class with ready-made equals(), hashCode() and toString().
  • extends — Declares inheritance: the class gets the parent's fields and methods.

In the tutorial

  • Classes and objects — What classes and objects are in Java: fields, methods, the new operator, default values and object references.

Thanks for reading!

Donate to the site — we work hard for you.