Classes, fields, constructors, methods
Model the world with classes — encapsulation, constructors, the `this` reference, and method overloading.
Runs on a sandboxed JVM via the public Piston API. Edit the code and hit Run.
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.
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.
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..
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.
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.
Runs on a sandboxed JVM via the public Piston API. Edit the code and hit Run.
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.
Related lessons & next topics
Keep going — these pair well with Classes, fields, constructors, methods.
- § 2.02 · Object-Oriented JavaInterfaces, abstract classes, inheritance
Polymorphism done right — when to extend, when to implement, and why composition usually wins.
Intermediate · 28 min - § 1.03 · FoundationsControl flow: if, switch, and loops
Branching and iteration, including modern switch expressions and the enhanced for loop.
Beginner · 20 min - § 1.02 · FoundationsVariables, primitive types, and references
The eight primitive types, the difference between values and references, and how the compiler infers types.
Beginner · 18 min - § 3.01 · Collections & GenericsLists, Sets, Maps — the Collections framework
ArrayList, HashMap, HashSet, and the Iterable contract. Choose the right structure for the job.
Intermediate · 30 min