Java Fundamentals, Part 2: Classes, Objects, and OO Thinking
Java & Spring Boot for Beginners · Part 4 of 14
- #Java
- #Spring Boot
- #Beginners
- #Fundamentals
In Part 3 we built
TicketPricer out of variables, operators, and control flow — a static method
that took an age, a day, and a flag, and handed back a number. That's a
perfectly real program. It's also the last time in this series we write Java
that way.
Everything from here on models things: a customer, a ticket, a booking. Not
because that's more "proper," but because most of what makes a program hard to
maintain is data and the rules around it drifting apart — a boolean isStudent here, the discount logic that reads it three files away, and no
way to tell they're related without reading everything. A class is Java's
answer to that: put the data and the code that's allowed to touch it in one
place, give it a name, and let the rest of the program deal with the name
instead of the details.
A class is a blueprint, an object is the real thing
A class declares what a kind of thing looks like and what it can do. An object is one actual instance of that thing, sitting in memory with its own values. You write the class once; you can make as many customers as you want.
public class Customer {
private final String name;
private final int age;
private final boolean isStudent;
public Customer(String name, int age, boolean isStudent) {
if (age < 0) {
throw new IllegalArgumentException("age can't be negative: " + age);
}
this.name = name;
this.age = age;
this.isStudent = isStudent;
}
public String name() {
return name;
}
public double discountMultiplier() {
if (age < 16) return 0.5;
if (age >= 65 || isStudent) return 0.7;
return 1.0;
}
}
new Customer("Ana", 9, false) builds one object: memory allocated, the
constructor runs, and you get back a reference to it — the same kind of
reference Part 3 talked about for String. Every field, method, and line of
this class is defined once; every Customer you create gets its own copy of
the fields but shares the same code.
A few things worth naming explicitly:
thisrefers to the object the method or constructor is currently running on.this.age = agedisambiguates the field from the constructor parameter of the same name — a very common pattern, not a special trick.- The constructor is just a method that shares the class's name and runs
once, at creation. It's the natural place to validate — reject a negative
age here and no
Customerin your program can ever hold one, instead of checking for it at every call site that uses one. discountMultiplier()is the same branching logicTicketPricerhad in Part 3, just living next to the data it reads instead of taking that data as parameters. That's the whole shift this post is about.
Encapsulation: state is private, behavior is public
Notice the fields are private. Nothing outside Customer can read or write
age or isStudent directly — the only way in is the constructor, and the
only way to ask anything about the customer is a method you've deliberately
written, like discountMultiplier().
This is encapsulation, and the habit worth building early is: don't just
expose raw fields with getters and setters and let other classes make
decisions about your data. Ask the object to do the work instead. If
Ticket needs to know the price, it shouldn't reach into Customer's age
and re-derive the discount rule itself — that logic would end up duplicated
the moment a second class needs it, and the two copies will drift apart.
It asks customer.discountMultiplier() and gets an answer. The rule lives in
exactly one place.
You'll still write plenty of getters — name() above is one, and there's
nothing wrong with a method that just returns a field. The distinction is
between exposing data and exposing decisions. Keep the decisions inside
the class that owns the data they're based on.
References, revisited
Part 3 showed that an object variable holds a reference, not the value itself. That matters more once you're writing your own classes, because assignment between two variables of a class type doesn't copy the object — it copies the reference. Both variables end up pointing at the exact same thing:
int[] scores = {10, 20, 30};
int[] sameScores = scores;
sameScores[0] = 999;
System.out.println(scores[0]); // 999 — same array, not a copy
Arrays are objects, so this is the same rule Part 3's String diagram
hinted at, just with a mutation this time. The exact same thing happens with
any class you write: Customer sameCustomer = customer; doesn't clone
anything, it hands out a second name for the same object. Mutate through
one variable and every other variable pointing at that object sees the
change — there's only one object to see.
This is exactly why I made Customer's fields final and gave it no
setters. There's no way to mutate a Customer after it's built, so aliasing
like this can't bite you — every reference to it sees the same, unchanging
state, which is one less category of bug to reason about. When a class
does need to change over time (an entity backed by a database row is the
usual case, and we'll get there in Part 10), the aliasing behavior is exactly
why: two parts of the code holding the same reference need to see each
other's changes. Immutable by default, mutable when you have a specific
reason — same instinct as final on a local variable in Part 3.
A little inheritance, and interfaces
Say Ticket computes a price from a Customer and a day of the week — the
same rules TicketPricer had, just reorganized:
public class Ticket implements Priceable {
private static final double BASE_PRICE = 12.50;
private final Customer customer;
private final DayOfWeek day;
public Ticket(Customer customer, DayOfWeek day) {
this.customer = customer;
this.day = day;
}
@Override
public double price() {
double price = BASE_PRICE * customer.discountMultiplier();
return Math.max(0, price - matineeDiscount());
}
private double matineeDiscount() {
return switch (day) {
case MONDAY, TUESDAY, WEDNESDAY -> 2.00;
case THURSDAY -> 1.00;
default -> 0.00;
};
}
}
Priceable is an interface — a contract with no implementation of its own,
just a promise that anything implementing it can be asked for a price:
public interface Priceable {
double price();
}
That lets me write a GroupBooking that totals up anything Priceable
without caring what it actually is:
public class GroupBooking implements Priceable {
private final Ticket[] tickets;
public GroupBooking(Ticket... tickets) {
this.tickets = tickets;
}
@Override
public double price() {
double total = 0;
for (Ticket ticket : tickets) {
total += ticket.price();
}
return total;
}
}
(That Ticket... tickets is a varargs parameter — call
new GroupBooking(ticket1, ticket2, ticket3) with as many tickets as you
want, and inside the constructor it's just an array, same for-each as
always.)
Now say the cinema adds season passes: already paid for, always free at the
door. Inheritance lets SeasonPassTicket reuse everything Ticket has and
override just the one method that differs:
public class SeasonPassTicket extends Ticket {
public SeasonPassTicket(Customer customer, DayOfWeek day) {
super(customer, day);
}
@Override
public double price() {
return 0.0; // already paid for the season
}
}
extends means "is a kind of" — a SeasonPassTicket is a Ticket, and by
extension a Priceable, so it drops straight into GroupBooking alongside
regular tickets without GroupBooking knowing or caring that it's special.
super(customer, day) calls the parent constructor to set up the fields
Ticket already owns.
Use inheritance for genuine "is a kind of" relationships like this one. It's
tempting to reach for it any time two classes share some code, but a deep
extends chain gets fragile fast — a change to a grandparent class can break
something three levels down in a way that's hard to see coming. When what
you actually want is "these unrelated classes can all do X," that's what an
interface is for, and it's usually the better default. Priceable is doing
exactly that here.
Records: when a class is just data
Not everything needs behavior. A receipt after a booking is closed — nothing
to compute, nothing to protect, just a fact to carry around. Writing that as
a full class means a constructor, fields, getters, equals(), hashCode(),
and toString() by hand. A record gives you all of it in one line:
public record TicketReceipt(String customerName, double amountPaid, DayOfWeek day) {}
That's a complete, immutable type: a constructor, three accessor methods
(customerName(), amountPaid(), day()), and generated equals(),
hashCode(), and toString() that all compare and print the actual field
values — not the default object-identity noise you get from a plain class
that doesn't bother to write those. You can still validate, with a compact
constructor that runs before the fields are assigned:
public record TicketReceipt(String customerName, double amountPaid, DayOfWeek day) {
public TicketReceipt {
if (amountPaid < 0) {
throw new IllegalArgumentException("amountPaid can't be negative");
}
}
}
The rule of thumb I use: if a type's whole job is to hold data, reach for
a record. If it has real behavior tied to its own state — Ticket deciding
its price, Customer deciding its discount — write a class. You'll see this
distinction again once we get to Spring: request and response bodies for a
REST API are usually records, because they're just data crossing a wire;
the objects Spring wires together to do actual work are classes with
constructors, and Spring calls those constructors for you instead of you
writing new — which is most of what dependency injection turns out to be.
Putting it together
Customer ana = new Customer("Ana", 9, false);
Customer luis = new Customer("Luis", 70, false);
GroupBooking booking = new GroupBooking(
new Ticket(ana, DayOfWeek.TUESDAY),
new SeasonPassTicket(luis, DayOfWeek.TUESDAY)
);
TicketReceipt receipt = new TicketReceipt("Ana's party", booking.price(), DayOfWeek.TUESDAY);
System.out.println(receipt);
// TicketReceipt[customerName=Ana's party, amountPaid=4.25, day=TUESDAY]
Same pricing rules as Part 3's TicketPricer, same result for the same
inputs — but now the age-and-discount logic lives inside Customer, the
day-and-matinee logic lives inside Ticket, GroupBooking doesn't need to
know either exists, and a SeasonPassTicket slots in without anyone editing
a switch statement to special-case it.
What to take away
- A class is a blueprint; an object is an instance of it, created
with
newand holding its own copy of the fields. - Encapsulation means private fields and public methods that expose decisions, not raw data — keep the rule for using a value next to the value itself.
- Assignment copies the reference, not the object. Two variables can
point at the same object; mutate through one and the other sees it too.
Immutability (
finalfields, no setters) is how you opt out of that risk when you don't need it. - Interfaces say "can do X" and are usually the better default;
inheritance (
extends) says "is a kind of" and is worth it for genuine hierarchies, sparingly. - Records are for data with no behavior of its own — one line instead of a class's worth of boilerplate.
Type Customer, Ticket, and GroupBooking out, run the example, then
break something on purpose — make Customer mutable and watch aliasing bite
you, or add a second Priceable implementation and see how little
GroupBooking has to change. Next up we'll stop reaching for raw arrays
and get into collections and generics — the tools for handling a group of
these objects properly instead of a fixed-size Ticket[].