Classes
A class is a named blueprint for objects. It declares the data each object holds and the operations allowed on that data. In Java it is also the smallest unit of code: every field and method lives inside one.
Detailed Explanation
A class is two descriptions bundled together: a description of state, and a description of behaviour. Say you are modelling a payment. A payment has a reference number and an amount. It can be refunded, and it can be printed in a log line. The class Payment names that data and those operations in one place, so the rest of the program can handle "a payment" as a single idea instead of three loose variables that must be passed around in the right order.
Java pushes this harder than most languages. There is no top-level function and no free-floating variable. Every method and every field belongs to some type declaration. Before you write your first line of logic, you have already written a class.
Why classes exist. Procedural code kept data in one place (a struct, a record, a row) and behaviour in functions somewhere else. Nothing connected them, so any function anywhere could set a negative balance or an empty reference number. A class lets you put the rules next to the data, then close the door with private so the only way to change the state is through a method that checks the rules. That pairing is the whole point; the syntax is secondary.
How it behaves at runtime. A class is loaded by a class loader the first time it is actually needed. At that moment, and only once, its static fields and static initializer blocks run. Each new then creates an instance on the heap with its own copy of the instance fields. Those fields are first set to their defaults (0, false, null), then by field initializers and constructor bodies, in that order. So static members exist once per class per class loader, and instance members exist once per object.
A class can declare five kinds of member: fields, methods, constructors, initializer blocks, and nested types. Modifiers change the meaning substantially. static moves a member from the object to the class. final forbids reassignment. The access modifiers decide who can see it.
Every class you write extends java.lang.Object unless you name another superclass. That is why every object already has equals, hashCode, toString, getClass, and the wait/notify methods. Those are contracts, not decoration. Put your class into a HashMap and its equals and hashCode decide whether lookups find anything.
When to reach for one. Reach for a class when data and rules travel together, or when behaviour must vary between cases. If you have data and nothing else, a record (Java 16+) says it in a fraction of the code. If you have behaviour and no state, a final class of static methods, or an interface with static methods, communicates that better.
What it costs. Every object carries a header, typically 12 or 16 bytes on HotSpot, so a million small objects is real memory and real garbage collection work that a primitive array would avoid. Classes also cost design attention: one class with 30 fields and 40 methods is harder to reason about than three focused ones. And every public member is a promise. Once published, removing it breaks callers.
Code Examples
Payment.java — one public top-level class per file, named after the file.
// Payment.java — one public top-level class per file, named after the file.
public class Payment {
// Fields hold per-object state. 'private' keeps them out of a caller's reach.
private final String reference; // 'final': assigned once, inside the constructor
private long amountMinor; // amount in the smallest unit (paise or cents)
// A constructor runs when the object is created.
public Payment(String reference, long amountMinor) {
this.reference = reference; // 'this.' picks the field over the parameter
this.amountMinor = amountMinor;
}
// Instance method: needs an object to call it, and can read that object's fields.
public long amountMinor() {
return amountMinor;
}
// The rule lives next to the data it protects.
public void refund(long partMinor) {
if (partMinor > amountMinor) {
throw new IllegalArgumentException("cannot refund more than charged");
}
amountMinor -= partMinor;
}
// Static member: belongs to the class, not to any one object.
public static Payment ofRupees(String reference, long rupees) {
return new Payment(reference, rupees * 100);
}
@Override
public String toString() {
return "Payment[" + reference + ", " + amountMinor + "]";
}
public static void main(String[] args) {
var p = Payment.ofRupees("INV-9", 250); // 'var' infers the type Payment
p.refund(5_000);
System.out.println(p); // prints: Payment[INV-9, 20000]
}
}Counter.java — static state belongs to the class, instance state to each object.
// Counter.java — static state belongs to the class, instance state to each object.
public class Counter {
private static int created = 0; // one copy shared by the whole class
private final int id; // one copy per object
public Counter() {
created++; // mutates class-level state
this.id = created; // reads it into per-object state
}
public int id() {
return id;
}
public static int createdCount() {
return created; // a static method cannot touch 'id'; there is no object here
}
public static void main(String[] args) {
new Counter();
Counter second = new Counter();
System.out.println(second.id()); // prints: 2
System.out.println(Counter.createdCount()); // prints: 2
}
}Common Gotchas
Filename must match the public class
a source file may hold only one `public` top-level class, and the file must be named after it. `public class Payment` has to live in `Payment.java` or compilation fails.
Fields get silent defaults, locals do not
an uninitialised local variable is a compile error, but an uninitialised field is quietly `0`, `false`, or `null`. A forgotten assignment shows up later as a `NullPointerException` rather than at compile time.
Static mutable state is shared across threads
the `created` counter above is not thread-safe. Two threads calling `new Counter()` can read the same value and produce duplicate ids. Use `AtomicInteger` or synchronise.
Every class already extends `Object`
you inherit `equals`, `hashCode`, `toString`, and the monitor methods whether you want them or not. The defaults use object identity, which is rarely what you want for value-like data.