Classes & objects
Fields, methods, creating objects with new, references, null and toString.
So far we have written everything as static methods working on primitives, strings and arrays. That works for small programs, but real software models things: customers, orders, bank accounts, game characters. Object-oriented programming (OOP) lets you bundle the data about a thing together with the behaviour that operates on it.
Classes and objects#
- A class is a blueprint. It describes what data a thing has (fields) and what it can do (methods).
- An object is a concrete instance built from that blueprint. You can create as many objects from one class as you like, each with its own data.
Think of Car as a class: every car has a colour, a model and a speed, and can accelerate and brake. Your red hatchback and my blue SUV are two objects of that class.
Your first class#
These are instance fields and methods: they belong to each individual object. Notice there is no static keyword. Inside label(), title means "the title of the book this method was called on".
Creating and using objects#
new creates an object; the dot . accesses its fields and methods:
Each new Book() creates an independent object in memory. Changing a never affects b.
One file, several classes: a
.javafile may contain several top-level classes, but at most one can bepublic, and it must match the filename. That is handy for small examples like the one above. In real projects, put each class in its own file (Book.java,Library.java) in the same folder, and compile withjavac *.java.
Default values of fields#
Unlike local variables, fields get default values automatically when an object is created:
So a fresh new Book() has title == null and pages == 0. Setting every field by hand after new is tedious and error-prone. The next lesson introduces constructors, which initialise an object in one step.
References: variables point to objects#
A variable of a class type does not contain the object itself; it holds a reference (an arrow) to an object living on the heap:
== on references asks "do these point to the same object?". Whether two different objects are "equal" in content is decided by the equals method, which you will learn to write in the equals() & hashCode() lesson.
null and NullPointerException#
A reference variable can hold null, meaning "no object". Calling a method or reading a field through null throws a NullPointerException (NPE), the most famous runtime error in Java:
Modern JVMs give helpful messages that name the culprit:
Protect against it by checking if (missing != null), by always initialising fields, and later with Optional.
Methods can use and change state#
Methods are where the behaviour lives. They can read fields, change them, take parameters and return results:
Code outside the class can still write acc.balance = -999; and bypass the checks in withdraw. The encapsulation lesson shows how private fields prevent that.
toString(): a readable description#
Every class secretly extends Object, which provides a toString() method. Printing an object calls it. The default output is not very helpful:
Override it to describe your object:
@Override asks the compiler to verify you really are overriding a parent method. It will catch typos like tostring(). You will learn more in the inheritance and polymorphism lessons.
Objects working together#
Fields can hold other objects, and methods can take objects as parameters. This is how real systems are built:
The four pillars of OOP#
You will study each in its own lesson:
- Encapsulation: hide internal data behind a public interface.
- Inheritance: build specialised classes from general ones.
- Polymorphism: treat different objects through a common type, with each responding in its own way.
- Abstraction: expose what something does, hiding how.
Common mistakes#
- Forgetting
new:Book b; b.title = "x";does not compile, becausebwas never assigned an object. - Confusing the class with an object:
Book.titledoes not work for an instance field; you need an object, as inb.title. - Assuming
b = acopies an object. - Calling instance methods from
static mainwithout an object.
What's next#
Setting fields one by one after new is clumsy. Next you will learn constructors and the this keyword to create fully initialised objects in one line.
Check your understanding
Quick quiz
1.What is an object?
2.After
Dog a = new Dog("Rex"); Dog b = a; b.name = "Max";, what isa.name?3.What happens when you call a method on a variable that holds
null?
Finished reading?
Mark this lesson complete to track your progress.