Classes and Objects
The most important page in the course — what a class is, what an object is, and why every Java program after this looks completely different
A class is a blueprint. An object is a thing built from that blueprint. This sentence is the entire course in compressed form. If you internalize the difference, the rest of Java becomes a matter of vocabulary.
The blueprint vs the thing built from it
Think of the architect's drawing of a house. The drawing says "three bedrooms, two bathrooms, a kitchen." You cannot live in the drawing. You live in a particular house built from the drawing. From the same drawing you can build many houses, each at its own address, each with its own occupants.
In Java, the keyword class declares a blueprint. The keyword new
builds an object from it. Each object has its own copy of the
class's fields (its state) and can respond to the class's
methods (its behavior).
Your first real class
Pay attention to the punctuation:
class Dog { ... }— the blueprint.new Dog("Rex", 4)— calls the constructor, which builds an object.rexandlunaare two different objects. Each has its ownnameandage. Callingrex.haveBirthday()changesrex.age, notluna.age.
That last point is the entire reason classes are useful: each object keeps its own state.
A picture of two objects in memory
The variables rex and luna live in the stack frame of main.
The actual Dog objects live on the heap. Each variable holds a
reference — an arrow — to its own object.
This is the reference type picture from the variables lesson, now applied to a class you wrote yourself.
The anatomy of a class
A class declaration typically has three sections:
| Part | Purpose |
|---|---|
| Fields | The state every instance carries |
| Constructor(s) | How to bring a valid new instance into existence |
| Methods | The behavior — what every instance can do |
We will meet static members in a future page; ignore them for now.
Multi-file convention: one public class per file
Real Java programs put each public top-level class in its own file, named exactly like the class. From now on, when an example has more than one class, we will show each in its own file.
A few things to notice:
private finalfields —privatemeans no code outsideBookcan touch them;finalmeans they cannot be reassigned after the constructor finishes. We are saying: aBook's title, author, and year are part of its identity and must not change.title(),author(),year()are accessor methods (getters) — they answer questions about state without exposing the fields themselves.olderThan(Book other)takes anotherBookas a parameter. Because the comparison happens insideBookitself, it can accessother.yeareven thoughyearis private.
this: the object the method is running on
Every non-static method has an invisible parameter called this. It
refers to the object the method was called on. When you write
rex.describe(), inside describe, this is rex. When you write
luna.describe(), inside the same method body, this is luna.
You usually do not have to type this. You must type it when you
have a parameter or local variable with the same name as a field —
which is why constructors so often look like this.name = name;.
null and what happens when there's no object
A reference variable that does not yet point to any object holds the
special value null. Calling a method on null throws a
NullPointerException — Java's most famous error.
We will return to exceptions later. For now: when you see
NullPointerException, it means you tried to use an object that
wasn't there.
Which sentence correctly distinguishes a class from an object?
They are exactly the same thing
An object is the blueprint; a class is one specific instance
A class is a blueprint describing structure and behavior; an object is one specific instance created from that blueprint
A class is for primitives; an object is for reference types
Inside a method called on rex, what does this refer to?
The class Dog itself
The most recently created Dog
The specific Dog object the method was called on — that is, rex
A reserved field automatically present on every object
A small challenge
Create a class Counter with:
- A private
intfieldvaluethat starts at0. - A method
void bump()that increasesvalueby 1. - A method
int value()that returns the current value.
Main.java is fixed. It must print exactly:
c=3
d=1
The fact that c and d keep separate counts, even though both are
the same kind of object, is the heart of object-oriented programming.
Next we make the rules around fields explicit: encapsulation and
abstraction.
Methods and Modularity
Why we group instructions into named methods, how they call each other, and how a small program can be a graceful conversation between many small methods
Encapsulation and Abstraction
The two ideas that turn a collection of classes into a maintainable program — hide what callers should not see, expose what they need