Java Programming
Java Object-Oriented Basics: Classes, Objects, Fields and Methods
Beginner9 min readReviewed by Mariem Ouled on Updated
This guide explains the object model that everything else in Java builds on: what a class describes, what an object really is in memory, how constructors and methods work, why encapsulation matters and when a record replaces a hand-written class. After reading it you will be able to design a small, correct class and explain what happens at each line of a program that uses it.
What you will learn
- Distinguish a class from an object and a reference from the object it points to
- Write constructors, getters and methods that keep an object's state valid
- Choose between instance and static members deliberately
- Implement equals, hashCode and toString correctly, or let a record do it
- Explain how arguments are passed to Java methods and why it is not pass-by-reference
Java is an object-oriented language in the specific sense that nearly every line of code you write lives inside a class, and nearly every value you handle beyond the eight primitive types is an object reached through a reference. Getting this model right early pays off for years: most confusing bugs beginners meet — a NullPointerException, a method that "does not change" the variable passed to it, two "equal" objects that a HashSet treats as different — come from a fuzzy picture of what a class, an object and a reference are. This guide builds that picture with code that compiles on Java 21.
Classes describe, objects exist
A class is a blueprint: it declares what state (fields) and behaviour (methods) a kind of thing has. An object is one concrete instance created from the blueprint at run time, living in the heap with its own copy of every instance field. You create objects with new, and the result of new is a reference — a value that points at the object, not the object itself.
public class BankAccount {
private final String iban; // set once, never changes
private long balanceCents; // mutable state, kept private
public BankAccount(String iban, long openingBalanceCents) {
if (openingBalanceCents < 0) {
throw new IllegalArgumentException("Opening balance cannot be negative");
}
this.iban = iban;
this.balanceCents = openingBalanceCents;
}
public void deposit(long cents) {
if (cents <= 0) throw new IllegalArgumentException("Deposit must be positive");
balanceCents += cents;
}
public long balanceCents() {
return balanceCents;
}
}
BankAccount a = new BankAccount("FR7630006000011234567890189", 10_000);
BankAccount b = a; // b now refers to the SAME object as a
b.deposit(500);
System.out.println(a.balanceCents()); // 10500 — there is only one account
The second snippet is where the reference model matters. b = a does not copy the account; it copies the arrow. Both variables point at one object, so a change through b is visible through a. If you want a second, independent account you must create one with new.
The word this inside a method means "the object this method was called on". You mostly need it to disambiguate a field from a parameter of the same name, as in the constructor above.
Primitives versus references
Java has eight primitive types (int, long, double, boolean, char, byte, short, float) whose variables hold the value directly. Every other type — String, arrays, your own classes — is a reference type. A reference variable can also hold null, meaning "points at nothing", and dereferencing null (calling a method or reading a field through it) throws NullPointerException. Since Java 15 the message says by default which expression was null (because "order.customer" is null), which makes these far quicker to diagnose than they used to be.
The wrapper classes Integer, Long, Double and friends are reference types that box a primitive so it can live in a collection. Auto-boxing hides the conversion, but not the consequences: Integer values can be null, and comparing two Integer objects with == compares references, not numbers. Use equals or unbox first.
Constructors and object initialisation
A constructor runs exactly once per object, when new executes, and its job is to leave the object in a valid state. Three rules make constructors behave:
- If you declare no constructor, the compiler supplies a public no-argument one. As soon as you declare any constructor, that default disappears.
- A constructor may call another constructor of the same class with
this(...)as its first statement, which avoids duplicating validation logic. - Fields you do not assign get default values:
0,falseornull. For afinalfield, the compiler forces you to assign it in every constructor.
public class Temperature {
private final double celsius;
public Temperature(double celsius) {
this.celsius = celsius;
}
public Temperature() {
this(20.0); // delegate, do not repeat
}
public static Temperature ofFahrenheit(double f) { // static factory
return new Temperature((f - 32) * 5 / 9);
}
public double celsius() { return celsius; }
}
The ofFahrenheit method shows the static factory idiom: a static method that returns an instance. Factories can have descriptive names, can return a cached instance instead of a new one and can return a subtype, none of which a constructor can do. Many JDK types use them: List.of, Integer.valueOf, LocalDate.of.
Prefer validating in the constructor and throwing IllegalArgumentException over accepting anything and checking later. An object that can only exist in a valid state is far easier to reason about than one that must be checked before every use.
Encapsulation: fields private, intent public
Encapsulation means an object controls its own state. Concretely: declare fields private, expose behaviour through methods, and make the public surface as small as it can be. The point is not ceremony; it is that every rule about the state lives in one place. If balanceCents were public, the "never negative" rule would have to be re-checked by every piece of code that touches it.
Getters and setters are the mechanical way to expose state, and IDEs generate them in a keystroke, which is exactly why they get overused. A class whose API is getX/setX for every field is a struct with extra steps. Ask instead what operations the object supports — deposit, withdraw, close — and expose those. Where a plain accessor is right, modern Java style often drops the get prefix, matching what records generate.
The access modifiers, from most to least restrictive:
| Modifier | Visible from |
|---|---|
private | The declaring class only (including its nested classes) |
| (none, "package-private") | Any class in the same package |
protected | Same package plus subclasses in any package |
public | Everywhere |
Package-private is underused. A helper class that only the package needs should have no modifier at all; it keeps the public API of a library honest.
Immutability
An immutable object never changes after construction: all fields final, no setters, and any mutable component (a List, a Date, an array) defensively copied on the way in and out. Immutable objects are safe to share between threads, safe to use as map keys and safe to cache. String, LocalDate, BigDecimal and all the wrapper classes are immutable, and the collections returned by List.of and Map.of are unmodifiable. Reach for immutability by default and add mutability only where the domain needs it.
Methods, overloading and how arguments travel
A method has a name, a return type (or void), parameters and a body. Two methods in one class may share a name if their parameter lists differ; this is overloading, and the compiler picks the version by the static types of the arguments at the call site. Overloading on types that auto-box or widen into each other (int versus long versus Integer) leads to surprising choices, so keep overloads obviously distinct.
Java passes every argument by value. For a primitive, the value is the number. For an object, the value is the reference. The method receives its own copy of the reference, pointing at the same object:
static void rename(Person p) {
p.setName("Grace"); // mutates the shared object — caller sees this
p = new Person("Ada"); // rebinds the local copy — caller does NOT see this
}
After rename(person) runs, person.getName() is "Grace". The reassignment on the second line only changed the method's own variable. This single fact explains most "Java is pass-by-reference, no it isn't" arguments.
Variable-arity parameters (String... parts) let a method accept zero or more arguments of one type; inside the method they are an array. Put the varargs parameter last and avoid overloading a varargs method, because the compiler's choice becomes hard to predict.
Static members: the class-level namespace
A static field or method belongs to the class rather than to any instance. There is one copy, initialised when the class is first loaded, and you call it as Math.max(a, b) or Temperature.ofFahrenheit(98.6) without an object. Use static for:
- Constants:
public static final int MAX_RETRIES = 3; - Pure utility functions that operate only on their arguments (
Math,Collections,Objects). - Factory methods, as shown earlier.
Do not use static for state that logically belongs to an object, and be wary of mutable static state in general: it is global, shared by all threads and invisible to tests. A static method cannot use this and cannot be overridden, so heavy use of static also blocks polymorphism, which the next guide covers.
The static keyword on a nested class means the nested class does not capture a reference to an enclosing instance. Almost every nested class should be static; an inner (non-static) class silently keeps its outer object alive, which is a classic memory-leak source.
equals, hashCode and toString
Every class inherits three methods from java.lang.Object that you will override often.
toString() returns a human-readable description. The default (BankAccount@1b6d3586) is useless in logs; override it early.
equals(Object) defines when two objects count as the same value. The default compares references, so two distinct Money objects for €10 are unequal until you say otherwise. A correct override is reflexive, symmetric, transitive, consistent and returns false for null:
public final class Money {
private final long cents;
private final String currency;
public Money(long cents, String currency) {
this.cents = cents;
this.currency = Objects.requireNonNull(currency);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Money other)) return false; // pattern matching, Java 16+
return cents == other.cents && currency.equals(other.currency);
}
@Override
public int hashCode() {
return Objects.hash(cents, currency);
}
@Override
public String toString() {
return cents / 100 + "." + String.format("%02d", cents % 100) + " " + currency;
}
}
hashCode() must agree with equals: equal objects must produce the same hash. HashMap and HashSet use the hash to choose a bucket and only then call equals, so an inconsistent pair makes lookups fail in ways that look random. Never override one without the other, and never base either on a mutable field of an object you intend to put in a hash-based collection: changing the field after insertion makes the element unreachable.
Records: the compiler writes it for you
Since Java 16, a record declares an immutable data carrier in one line and generates the constructor, accessors, equals, hashCode and toString:
public record Money(long cents, String currency) {
public Money { // compact constructor: validation only
Objects.requireNonNull(currency);
if (cents < 0) throw new IllegalArgumentException("negative amount");
}
public Money plus(Money other) {
if (!currency.equals(other.currency)) throw new IllegalArgumentException("currency mismatch");
return new Money(cents + other.cents, currency);
}
}
The compact constructor has no parameter list and runs before the fields are assigned, which is the place for validation and normalisation. Records can have static factories, instance methods and can implement interfaces, but cannot declare extra instance fields or extend a class. When your class is "just data", a record is shorter, correct by construction and signals intent to readers.
A worked example
Putting the pieces together — a small order model with one entity class and two records:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
record Product(String sku, String name, long priceCents) {}
record OrderLine(Product product, int quantity) {
OrderLine {
if (quantity <= 0) throw new IllegalArgumentException("quantity must be positive");
}
long totalCents() { return product.priceCents() * quantity; }
}
public class Order {
private static long nextId = 1; // shared counter — fine for a single thread
private final long id;
private final List<OrderLine> lines = new ArrayList<>();
public Order() { this.id = nextId++; }
public void add(Product product, int quantity) {
lines.add(new OrderLine(product, quantity));
}
public long totalCents() {
long sum = 0;
for (OrderLine line : lines) sum += line.totalCents();
return sum;
}
public List<OrderLine> lines() {
return Collections.unmodifiableList(lines); // callers can read, not mutate
}
public long id() { return id; }
}
Order has identity (its id) and changes over time, so it is a class. Product and OrderLine are values, so they are records. The lines() accessor returns an unmodifiable view rather than the internal list — without it, a caller could order.lines().clear() and bypass every rule in the class. The static counter works here but is not thread-safe; the concurrency guide shows AtomicLong for the real thing.
Common mistakes
Comparing objects with ==. == on references asks "same object?", not "same value?". Use equals, and for strings in particular never rely on ==, even though interned literals sometimes make it appear to work.
Exposing internal collections. Returning the field itself from a getter hands out a handle to your private state. Return an unmodifiable view or a copy.
Overriding equals without hashCode. Explained above; the symptom is a HashSet that contains "duplicates" or a HashMap that cannot find a key.
Mutable static state. A static List<Order> allOrders is a global variable with a Java accent. It leaks memory, breaks tests that run in one JVM and is unsafe under concurrency.
Constructors that do real work. Opening files, connecting to databases or starting threads in a constructor makes the class impossible to test in isolation and leaks a half-built object if the work throws. Construct cheaply; do the work in an explicit method.
Non-static nested classes by accident. An inner class holds a hidden reference to its enclosing instance. Declare nested helpers static unless you actually need that reference.
Forgetting that fields have defaults. An unassigned int is 0 and an unassigned reference is null, silently. Assign in the constructor and make fields final where you can, so the compiler catches omissions.
Best practices
- Make every field
privateand every classfinalunless designed for extension. - Prefer immutable value types; records are the default choice for them since Java 16.
- Validate in constructors and compact constructors so invalid objects cannot exist.
- Implement
toStringon anything that will appear in a log line. - Keep
equals/hashCodebased on immutable fields, and generate them (record, IDE orObjects.hash) rather than hand-rolling. - Use static only for constants, pure utilities and factories.
- Name classes as nouns, methods as verbs, and let the coding standards guide settle the rest.
Key takeaways
- A class is a blueprint; an object is an instance on the heap; a variable holds a reference to it. Assignment copies the reference, not the object.
- Constructors establish valid state; static factories are a more flexible alternative with meaningful names.
- Encapsulation puts every rule about a piece of state in one place: private fields, deliberate public methods, unmodifiable views of internal collections.
- Java is always pass-by-value; the value of an object argument is a reference, so methods can mutate but not rebind the caller's object.
equalsandhashCodemust be overridden together and built on stable fields; records generate both correctly.- Static members are class-level; use them for constants and utilities, not for object state.
Sources and further reading
Frequently asked questions
- Is Java pass-by-reference or pass-by-value?
- Strictly pass-by-value. For an object argument, the value copied is the reference, so the method can modify the object's fields but cannot make the caller's variable point at a different object. Reassigning the parameter inside the method has no effect outside it.
- When should I use a record instead of a class?
- Use a record when the type is a transparent, immutable carrier of data: a point, a money amount, a DTO, a key in a map. Use a class when the object has mutable state, needs to hide its representation, or has a lifecycle with behaviour that is more than a set of accessors.
- Why must I override hashCode when I override equals?
- HashMap and HashSet find an element by hashCode first and only then call equals. If two objects are equal but return different hash codes, a set will happily hold both and a map will fail to find a key you just inserted. The contract in java.lang.Object requires equal objects to have equal hash codes.
- What is the difference between a static field and an instance field?
- An instance field has one value per object; a static field has one value per class, shared by every instance and accessible without any instance. Static is for constants, counters shared across all objects and utility methods, not for state that belongs to a particular object.