← Java tutorial

Java

Classes & Objects

A class is a blueprint describing what data (fields) and behaviour (methods) its instances will have. new ClassName(...) creates an object from that blueprint.

Example: a Student class and creating an instance

class Student {
    String name;
    String track;

    Student(String name, String track) {
        this.name = name;
        this.track = track;
    }
}

public class Main {
    public static void main(String[] args) {
        Student ada = new Student("Ada", "Frontend");
        System.out.println(ada.name + " is studying " + ada.track);
    }
}
Ada is studying Frontend

The block matching the class name (Student(String name, String track) {...}) is the constructor — it runs automatically every time new Student(...) is called, setting up that specific object's initial data. this.name = name distinguishes the object's own field (this.name) from the constructor's parameter (name), which otherwise share the identical name — a deliberate, very common naming convention, not a coincidence, and worth recognizing when you see it in real code.

Example
class Student {
    String name;
    String track;

    Student(String name, String track) {
        this.name = name;
        this.track = track;
    }
}

public class Main {
    public static void main(String[] args) {
        Student ada = new Student("Ada", "Frontend");
        System.out.println(ada.name + " is studying " + ada.track);
    }
}
Output
Ada is studying Frontend