Quiz
Warm-up from lesson 4-2: word.length() needs a String object to act on, while Math.sqrt(2.0) is called on the class itself. What are these two kinds of methods called?
Classes model things
Classes were invented to solve a scaling problem: in a big program, the data describing one thing (a user's name, email, balance) and the code that operates on it drift apart into different files, and every change breaks something. A class fuses them into one unit — this is the core move of object-oriented programming, and it is how essentially all large Java systems (and the entire standard library you have been using) are organized. String with its .length() is a class; now you build your own.
So far Main was just a wrapper. A class becomes interesting when it describes a kind of thing: what data each one carries (fields) and what each one can do (methods).
class Dog { String name; // field int age; // field void bark() { // instance method, no static System.out.println(name + " says woof"); } }
An object (or instance) is one concrete dog built from the blueprint:
Dog rex = new Dog(); rex.name = "Rex"; rex.bark();
new Dog() allocates a fresh object. Each object gets its own copy of the fields. Notice bark has no static: it belongs to one dog, and inside it, name means this dog's name.
Code exercise · java
Run this. Two Dog objects are created from one class. Each keeps its own name and age. A second class can sit in the same file below Main.
Fields start with default values
A local variable must be assigned before use — the compiler refuses otherwise. Fields are different: every field gets an automatic default value the moment new runs, because the object must be in some defined state before the constructor or your code fills it in. The defaults are zero-like: 0 for numbers, false for boolean, and null for every object type, including String.
Dog stray = new Dog(); stray.age // 0 stray.name // null — no String here yet
null means "this reference points at nothing". Calling a method through it (stray.name.length()) throws a NullPointerException, the most famous crash in Java. This is the practical reason the next lesson exists: constructors make sure no object ever leaves new half-empty.
Quiz
Right after Dog d = new Dog(); with no constructor and no assignments, what are d.name and d.age?
Code exercise · java
Your turn. Create a Book class with a String field title and an int field pages, plus a describe() method that prints `<title> has <pages> pages`. In main, build two books (Dune, 412 pages and Emma, 320 pages) and describe both.