← 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
Ready to go further?

These free tutorials are a preview, our Backend Development cohort covers it in depth, with a real project and a cohort alongside you. Closes Nov 30

Enroll in Backend Development

Cookie preferences

Choose what you're comfortable with. You can change this any time from the footer.

Don't miss out

Ready to build something real?

Create a free account to enroll in a track, and get notified the moment a cohort opens.

Create free account