← The curriculum
§ 2.01 · Object-Oriented Java

Classes, fields, constructors, methods

Model the world with classes — encapsulation, constructors, the `this` reference, and method overloading.

Beginner · 25 minute read
Try it yourself
Live Java · editable

Runs on a sandboxed JVM via the public Piston API. Edit the code and hit Run.

§ 2.01.01

A class bundles state and behavior

Fields hold state; methods define behavior. The private modifier hides fields from callers so the class controls how they change — this is encapsulation. Prefer private final fields whenever a value shouldn't change after construction.

§ 2.01.02

Constructors

A constructor initializes a new instance. It has no return type and shares the class name. You can define several constructors with different parameter lists (overloading); chain them with this(...) to avoid duplication. If you don't declare one, Java gives you a public no-arg constructor for free — unless any other constructor is present.

§ 2.01.03

The `this` reference

this is the current instance. Use it to disambiguate when a parameter shadows a field (this.x = x), to pass the current object to another method, or to invoke another constructor (this(...)). It's implicit for field access inside the same class, so most methods don't need to write this..

§ 2.01.04

Static members

Fields and methods marked static belong to the class, not to any instance. Math.sqrt and Integer.parseInt are static. Use static for utility helpers and constants (public static final double PI = 3.14159;). Static methods can't access instance state.

§ 2.01.05

Records — the modern data class

For simple value carriers, prefer a record. One line replaces a constructor, accessors, equals, hashCode, and toString. Records are implicitly final and their fields are final — perfect for DTOs and value objects.

Example
Live Java · editable

Runs on a sandboxed JVM via the public Piston API. Edit the code and hit Run.

§ 2.01.06

equals, hashCode, toString

The Object class defines these three. Reference equality (==) checks pointer identity; equals checks logical equality. If you override equals, you must override hashCode so hash-based collections still work. Let your IDE generate them from your fields, or use a record.