Java Foundations

Lesson 4 of 7

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 new an instance, setting up its initial state.
  • this refers to the specific instance a method was called on, needed here because the parameter name shadows the field name.
  • private fields can only be accessed from inside the class itself, forcing outside code to go through methods like gainXp/getXp instead 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.

📝 Methods and Classes Quiz

Passing score: 70%
  1. 1.What runs automatically when you create a new instance with "new Student(...)"?

  2. 2.A private field can be accessed directly from outside the class it is declared in.

  3. 3.Keeping fields private and only exposing controlled access through methods is called ____.