A class is a blueprint, an object is a thing
A class describes a kind of thing: what data it holds (fields) and what it can do (methods). An object is one concrete instance created from that class with new. Book is the class; the copy of a particular novel on your desk is an object. Each object has its own copy of the instance fields.
class Book {
String title; // fields: every Book object has its own
int pages;
boolean read; // fields get defaults: false here
void finish() { // a method that changes this object's state
read = true;
}
String describe() {
return title + " (" + pages + " pages)" + (read ? " - read" : "");
}
}
public class Main {
public static void main(String[] args) {
Book a = new Book();
a.title = "Clean Code";
a.pages = 464;
Book b = new Book();
b.title = "Refactoring";
b.pages = 448;
a.finish();
System.out.println(a.describe());
System.out.println(b.describe());
}
}Clean Code (464 pages) - read
Refactoring (448 pages)Two classes in one file: only one top-level class may be public, and the file is named after it. In real projects each class gets its own file.
Add a field String author and include it in describe(). What does it print before you set it?
Book a = new Book(); creates an object on the heap and stores a reference to it in a. Book c = a; copies the reference, not the book: c.pages = 1 changes the one object both names point at. This is the same rule you met with arrays in module 03.