Classes, Records, Fields, and Methods

Classes, Records, Fields, and Methods


Classes

A class is a blueprint for objects. It defines fields (state) and methods (behaviour):

java
public class Person { private String name; private int age; public String getName() { return name; } public int getAge() { return age; } }

Access Modifiers

Modifier Accessible from
private Same class only
(package) Same package
protected Same package + subclasses
public Everywhere

Fields

Instance fields belong to each object; static fields are shared across all instances:

java
public class Counter { private int count; // instance field private static int total; // shared across all Counter objects }

Field defaults (when not explicitly initialised):

Type Default
byte/short/int/long 0
float/double 0.0
boolean false
char ''
Object reference null

Local variables have no default — they must be initialised before use.


Methods

java
public double calculateArea(double radius) { return Math.PI * radius * radius; }
  • Return type must match the declared type (or be a subtype — covariant return).
  • A void method may use return; with no value.
  • static methods belong to the class and cannot access instance fields directly.

Method Signature

The signature is the method name + parameter types (not the return type):

java
void process(int x) // signature: process(int) void process(int x, int y) // signature: process(int, int) — overload int process(int x) // SAME signature as first → compile error

Records

A record is a concise, immutable data carrier (finalized in Java 16):

java
public record Point(double x, double y) { }

The compiler automatically generates:

  • private final fields for each component
  • A canonical constructor
  • x() and y() accessor methods
  • equals(), hashCode(), and toString()
java
Point p = new Point(3.0, 4.0); System.out.println(p.x()); // 3.0 System.out.println(p); // Point[x=3.0, y=4.0]

Customising Records

java
public record Range(int min, int max) { // compact canonical constructor — validates without repeating assignments Range { if (min > max) throw new IllegalArgumentException("min > max"); } // additional method public int size() { return max - min; } }

Record Restrictions

  • Fields are always private final — cannot add instance fields.
  • Cannot extend another class (implicitly extends Record).
  • Can implement interfaces.
  • Can be generic.

Key Differences: Class vs Record

Feature Class Record
Mutability Mutable by default Immutable (fields are final)
Boilerplate Manual equals, hashCode, toString Auto-generated
Inheritance Can extend classes Cannot extend classes
Extra fields Allowed Not allowed (components only)
v1.0·Last updated 2026-05-26