Lesson 2 of 23
In progress
A class is a blueprint
Create a class with fields and behaviour, make objects from it, and see why Java puts almost everything inside a class.
Java is an object-oriented language in a literal sense: almost every line you write lives inside a class. The good news is that a class is a modest idea — a named bundle of data and the operations on it.
What you will learn
- Declare a class with fields and methods.
- Create objects and call their methods.
- Tell a class from an instance.
A class with state and behaviour
public class Counter {
int value = 0;
void increment() {
value = value + 1;
}
int current() {
return value;
}
}
Counter has one field, value, and two methods. The field holds the object’s state; the methods change or read it.
A class is a blueprint. Nothing is stored until you create an object:
public class CounterDemo {
public static void main(String[] args) {
Counter a = new Counter();
Counter b = new Counter();
a.increment();
a.increment();
b.increment();
System.out.println(a.current());
System.out.println(b.current());
}
}
Two objects, two independent value fields. a prints 2 and b prints 1. Each new Counter() allocates a fresh object with its own copy of the instance fields.
Fields, local variables, parameters
- A field is declared inside the class and lives as long as the object.
- A local variable is declared inside a method and disappears when the method returns.
- A parameter is a local variable filled by the caller.
public class Temperature {
double celsius;
void raiseBy(double amount) {
double previous = celsius;
celsius = previous + amount;
}
}
celsius outlives raiseBy; previous and amount do not. Mixing the two up produces the classic bug of a value that resets on every call.
Methods with parameters and return values
public class Text {
String value;
Text(String value) {
this.value = value;
}
int length() {
return value.length();
}
String shout() {
return value.toUpperCase() + "!";
}
}
Text(String value) is a constructor: it runs on creation and sets up the object. this.value refers to the field, while value alone would be the parameter. Without this, the assignment would set the parameter to itself and leave the field null.
The two other methods show the two shapes a method can have: one returns a value, one computes a new value without changing the object.
Objects are references
Text a = new Text("hello");
Text b = a;
b.value = "changed";
System.out.println(a.value);
This prints changed. b = a copies the reference, not the object, so both variables point at the same instance. Java passes object references by value, which means a method can change an object’s fields but cannot make the caller’s variable point elsewhere.
That distinction explains a lot of surprising behaviour:
void reassign(Text t) {
t = new Text("other");
}
void mutate(Text t) {
t.value = "other";
}
Calling reassign(a) leaves a unchanged, because the method only reassigned its own local copy of the reference. Calling mutate(a) changes the shared object. This is the single most common source of confusion for newcomers arriving from languages with explicit pointers or with copy semantics.
Naming and file layout
One public class per file, with the file named after it. Helper classes can be package-private and live in the same file, though that is rare outside small examples.
Class names are nouns in PascalCase: Counter, Temperature, InvoiceLine. Method names are verbs in camelCase: increment, raiseBy, totalPaise. Fields are nouns in camelCase. Consistency matters more than any single choice, because readers scan for shape before meaning.
Why everything is in a class
Java’s design ties data to behaviour and uses classes as the unit of compilation, loading and access control. That has costs — a five-line script needs a class — and benefits: a class is a natural place to enforce the rules about its own data, and the compiler can check that the rules hold.
Modern Java has relaxed some of this with records and top-level methods in preview, but the class remains the default unit. Learning to design small, focused classes is the skill; the syntax is the easy part.
A complete example
public class BankAccount {
private long balancePaise;
BankAccount(long openingPaise) {
if (openingPaise < 0) {
throw new IllegalArgumentException("Opening balance cannot be negative");
}
this.balancePaise = openingPaise;
}
void deposit(long paise) {
if (paise <= 0) {
throw new IllegalArgumentException("Deposit must be positive");
}
balancePaise += paise;
}
long balancePaise() {
return balancePaise;
}
}
The field is private, the constructor validates, and every change goes through a method that checks its input. That is the shape most Java classes take, and it is why Java code tends to be verbose and hard to misuse.
Forgetting new and writing Counter c; followed by c.increment(). The variable is declared but points at nothing, so the call throws a NullPointerException. Declaring a reference does not create an object.
Write a Rectangle class with width and height, a method area() and a method scale(double factor) that multiplies both sides. Create two rectangles and show that scaling one does not affect the other.
Show solution
public class Rectangle { double width; double height; Rectangle(double width, double height) { this.width = width; this.height = height; } double area() { return width * height; } void scale(double factor) { width *= factor; height *= factor; } } Calling scale(2) on one rectangle doubles its fields only, because each object owns its own copies. Printing area() before and after shows the change, and the second rectangle’s area is untouched.
Recap
- A class bundles fields and methods; each
newcreates an object with its own fields. thisdistinguishes a field from a parameter of the same name.- Variables hold references, so assigning one to another shares the object rather than copying it.
Next, the primitive types and the rules that decide what fits in each one.
Can a class have no fields?
What is a record?
Progress is saved in this browser only. No account, no email.