Introduction
So far, data has lived in separate variables and arrays. Real programs model things: an account with an owner and a balance, a student with marks, a parcel with a weight. A class describes such a thing once, its data and what can be done with it, and each object made from it holds its own data. Java is built around classes; every program you have written has been one.
How it works
A class lists fields, the data each object holds, constructors, which set up a new object, and methods, what the object can do:
class Account {
private double balance;
Account(double opening) { this.balance = opening; }
void deposit(double amount) { balance += amount; }
}
new Account(100) creates an object and runs the constructor. Each object has its own fields, so two accounts have two balances. Inside methods, this means the current object; this.owner = owner copies the parameter into the field of the same name. A class can have several constructors, and one can call another with this(...). If you write no constructor, Java supplies an empty one.
Encapsulation means keeping fields private, so only the class's own code can touch them, and offering methods that enforce the rules: deposit refuses negative amounts, withdraw refuses to overdraw. A getter such as getBalance() lets others read a value without changing it. final fields can be set only in the constructor, which makes values such as an owner fixed for the object's life.
A static field belongs to the class, not to any object: there is one created counter shared by every account. Static methods are called on the class, Account.getCreated(), and cannot use this.
Every class inherits a toString() method that Java calls when an object is printed or joined to a string. The default shows the class name and a code; overriding it, marked @Override, makes printing meaningful.
Object variables hold references. Account same = a; does not copy the account; both names now reach the one object, so a withdrawal through same is seen through a. == on objects asks whether two references point at the same object.
Example
// A class with private fields, two constructors, methods, a static counter and toString.
class Account {
private static int created = 0; // one value for the whole class
private final String owner;
private double balance;
Account(String owner, double opening) {
this.owner = owner;
this.balance = opening;
created++;
}
Account(String owner) {
this(owner, 0); // calls the other constructor
}
void deposit(double amount) {
if (amount <= 0) throw new IllegalArgumentException("A deposit must be positive");
balance += amount;
}
boolean withdraw(double amount) {
if (amount > balance) return false;
balance -= amount;
return true;
}
double getBalance() {
return balance;
}
static int getCreated() {
return created;
}
@Override
public String toString() {
return owner + ": " + String.format("%.2f", balance);
}
}
public class Main {
public static void main(String[] args) {
Account a = new Account("Ada", 100);
Account b = new Account("Alan");
a.deposit(50);
boolean ok = b.withdraw(20);
System.out.println(a + " | " + b + " | " + ok);
Account same = a; // a second reference to the same object
same.withdraw(30);
System.out.println(a.getBalance() + " " + Account.getCreated());
}
}Line by line
Accounthas a static counter, a final owner and a private balance.- The one-argument constructor calls the two-argument one with an opening balance of 0.
withdrawrefuses to overdraw and reports it by returning false.- Printing an account calls its
toString. sameandarefer to the same object, so withdrawing throughsamechangesa's balance.
Expected result
Ada: 150.00 | Alan: 0.00 | false
120.0 2
In the real world
Business software is built from classes such as Customer, Order and Invoice, each guarding its own rules. Frameworks such as Spring create and connect objects for you, but they rely on the same ideas: private state, constructors and methods. Encapsulation is what lets a team change how a class works inside without breaking the code that uses it.
Common mistakes
- Making fields public so any code can put an object into an invalid state.
- Forgetting this when a parameter has the same name as a field, so the field is never set.
- Expecting = to copy an object; it copies the reference.
- Calling an instance method from static main without creating an object first.
Best practices
- Make fields private, and final where they never change.
- Validate arguments in constructors and methods, and throw an exception for invalid ones.
- Override toString for every class you will print or debug.
Summary
A class defines fields, constructors and methods; new creates objects, each with its own fields. Private fields with methods that enforce rules give encapsulation, this refers to the current object, static members belong to the class, toString controls printing, and object variables are references.
Quick check
Key takeaways
- A class bundles fields and methods; new makes an object with its own fields.
- Make fields private and let methods guard every change, so an object can never be invalid.
- An object variable holds a reference: copying it shares the object, it does not clone it.
Practice problems for this lesson
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.