Classes: Build Reusable Blueprints for Objects
Introduction
This chapter teaches classes in depth: fields, constructors, instance methods, and object creation. You already know Methods (including overloading and static); here the focus is instance state and encapsulation, not re-explaining overload/static rules.
Prerequisites
- Methods and OOP Overview
- Coding Standards naming conventions
What Is a Class (Recap)
A class defines attributes (fields) and behaviors (methods). Objects are instances.
public class Student {
private String name;
private int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public void introduce() {
System.out.println("I am " + name + ", score: " + score);
}
public int getScore() {
return score;
}
public void setScore(int score) {
if (score >= 0 && score <= 100) {
this.score = score;
}
}
}Student stu = new Student("Emma", 95);
stu.introduce();1) Fields (Instance Variables)
Fields hold per-object state.
public class Book {
private String title;
private int pages;
// constructor and methods follow
}Use private for fields and expose access through methods when you need control (Encapsulation).
2) Constructors
Constructors run when new creates an object. Name matches the class; no return type.
public class Book {
private final String title;
private int pages;
public Book(String title, int pages) {
this.title = title;
this.pages = pages;
}
}Default constructor
If you write no constructors, Java provides a no-arg default. If you write any constructor, the default is not generated unless you add it yourself.
public Book() {
this.title = "Untitled";
this.pages = 0;
}this keyword
this refers to the current object—disambiguates fields from parameters:
this.pages = pages;Constructor chaining: this(...) calls another constructor in the same class.
3) Instance Methods
Operate on the object’s fields:
public boolean isPassing() {
return score >= 60;
}
public void addBonus(int points) {
setScore(score + points);
}Call on an instance:
Student stu = new Student("Noah", 82);
stu.addBonus(5);4) Getters and Setters
Common pattern for encapsulated fields:
public String getName() {
return name;
}
public void setName(String name) {
if (name != null && !name.isBlank()) {
this.name = name.strip();
}
}Not every field needs a setter—immutable fields (e.g. id) may be getter-only.
5) Object Creation and References
Student a = new Student("Liam", 90);
Student b = a; // b points to same object as a
b.setScore(100);
System.out.println(a.getScore()); // 100new allocates an object; variables hold references (addresses), not the object itself.
null means no object:
Student s = null;
// s.getScore(); // NullPointerException6) toString Preview
Classes can override toString for readable printing (Object Class):
@Override
public String toString() {
return "Student{name='" + name + "', score=" + score + "}";
}7) Real Mini Example: Bank Account
public class BankAccount {
private final String owner;
private double balance;
public BankAccount(String owner, double initialBalance) {
this.owner = owner;
if (initialBalance >= 0) {
this.balance = initialBalance;
}
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
public boolean withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
return true;
}
return false;
}
public double getBalance() {
return balance;
}
@Override
public String toString() {
return owner + ": $" + balance;
}
}BankAccount account = new BankAccount("Alice", 100);
account.deposit(50);
account.withdraw(30);
System.out.println(account);Common Beginner Mistakes
Forgetting new
Student s = Student("Emma", 90); // error
Student s = new Student("Emma", 90);Shadowing Fields Without this
public void setScore(int score) {
score = score; // assigns parameter to itself
}Public Mutable Fields
Prefer private fields + controlled setters.
Mini Practice
Create class Rectangle with width, height, constructor, area(), perimeter(), and toString().
What’s Next
Type-safe containers: Generics, then Enums.
FAQ
How is a class different from a record?
record is for compact immutable data. Classes support richer behavior, mutable state, and inheritance hierarchies.
Do I need getters/setters for every field?
Use them when you need validation or stable APIs. Small learning classes sometimes use package-private fields—production code favors encapsulation.
What is final on a field?
The reference or value cannot be reassigned after construction (final String owner).
Can one file have multiple classes?
Yes, but only one public top-level class per file, and its name must match the filename.
When should methods be static?
When behavior does not depend on instance state (Math.max, factory helpers). Instance methods are the default for object behavior.