Classes & Objects
Class vs object
- A class is a blueprint: it describes what something has (fields) and does (methods).
- An object is a real thing built from that blueprint. One
Petclass can create many pets.
public class Pet {
String name; // fields (state)
int happiness;
void play() { // method (behaviour)
happiness += 10;
}
}
Pet buddy = new Pet(); // create an object with `new`
buddy.name = "Buddy";
buddy.play();
Constructors
A constructor sets up a new object. It has the same name as the class and no return type.
public Pet(String name) {
this.name = name; // this.name = field, name = parameter
this.happiness = 50;
}
- If you write no constructor, Java gives you a free empty one. Once you write any constructor, that free one disappears.
- Overload constructors to offer several ways to create objects.
- Call another constructor of the same class with
this(...)as the first line.
The this keyword
this means "the current object". Use it to tell fields apart from parameters with the same name.
static members
static fields and methods belong to the class, shared by every object:
static int petCount = 0; // one counter for all pets
toString()
Override toString() so printing an object shows something useful instead of Pet@1b6d3586.
Records (Java 16+) ✨
For simple data holders, one line gives you a constructor, getters, equals, hashCode and toString:
record Point(int x, int y) { }
Example
public class Pet {
private static int petCount = 0;
private final String name;
private int happiness;
public Pet(String name) {
this(name, 50); // calls the other constructor
}
public Pet(String name, int happiness) {
this.name = name;
this.happiness = happiness;
petCount++;
}
public void play() { happiness = Math.min(100, happiness + 10); }
@Override
public String toString() {
return name + " (happiness: " + happiness + ")";
}
public static void main(String[] args) {
Pet buddy = new Pet("Buddy");
buddy.play();
System.out.println(buddy); // Buddy (happiness: 60)
System.out.println(petCount); // 1
}
}