Methods and Classes
A class is a blueprint for objects, bundling data (fields) and behavior (methods) together, the foundation of Java's object-oriented style.
public class Student {
private String name;
private int xp;
public Student(String name) { // constructor
this.name = name;
this.xp = 0;
}
public void gainXp(int amount) {
this.xp += amount;
}
public int getXp() {
return this.xp;
}
}
Student ada = new Student("Ada");
ada.gainXp(50);
System.out.println(ada.getXp()); // 50
- The constructor (same name as the class, no return type) runs whenever you
newan instance, setting up its initial state. thisrefers to the specific instance a method was called on, needed here because the parameternameshadows the fieldname.privatefields can only be accessed from inside the class itself, forcing outside code to go through methods likegainXp/getXpinstead of reaching in and mutating state directly, this is encapsulation.
Why private fields plus public methods?
getXp()/gainXp() exist instead of a public xp field so the class controls how its state changes, e.g. gainXp could reject negative amounts, or trigger a level-up check, logic a bare public field could never enforce. This getter/setter pattern is one of the most common in all of Java.