Reference · module 5
Classes and objects
Everything this module explains, on one page.
A class and its objects
Define a class with fields and create objects from it.
- A class is a blueprint: class Dog { String name; int age; } describes what every dog has. Nothing exists yet — it is only a description.
- new creates an object from the class: Dog rex = new Dog(); rex.name = "Rex"; The variable rex refers to that one object.
- Each object has its own copy of the fields. Changing rex.age does not change the age of another Dog; they share the blueprint, not the values.
The mistake you are about to make
Dog rex; rex.name = "Rex";
Dog rex = new Dog(); rex.name = "Rex";
Declaring the variable feels like creating the dog. Without new there is no object, and using rex stops the program or does not compile.
Constructors and methods
Set up objects with a constructor and give them behaviour.
- A constructor runs when an object is created. It has the class name and no return type: Dog(String name) { this.name = name; } Then new Dog("Rex") sets the name at once.
- this means the current object. this.name is the field, name alone is the parameter — without this, name = name would just assign the parameter to itself.
- Methods without static belong to an object and use its fields: String bark() { return name + " says woof"; } Call them on an object: rex.bark().
The mistake you are about to make
void Dog(String name) { ... }
Dog(String name) { ... }
Every method so far had a return type, so void seems needed. A constructor has none; with void it becomes an ordinary method that never runs on new.
private and getters
Protect fields with private and expose them through methods.
- private makes a field visible only inside its class: private int balance; Code outside cannot write account.balance = -100; — it does not compile.
- A getter lets others read the value: public int getBalance() { return balance; } The class decides what is shown, without handing over the field itself.
- A method that changes the field can check the input first: deposit(int amount) refuses a negative amount. This is why fields are private: the class guards its own rules.
The mistake you are about to make
public int balance;
private int balance; public int getBalance() { return balance; }
A public field is shorter and seems to do the same job. Anyone can then set a negative balance, and the class cannot stop it.