ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Java Tutorial• 7 min read

Classes, Objects & Constructors

Instantiating objects, this keyword, default and parameterized constructors

Classes are blueprints from which individual object instances are created on the heap using the new operator.

Constructors & The this Keyword

Constructors share the exact name of the class with no return type.

this: Refers to the current calling instance, resolving ambiguity between class fields and parameter names.

Constructor Chaining: Calling this(...) as the first line delegates to another constructor in the same class.

Student Class with Constructors
public class Student {
    private String name;
    private int xp;

    // Parameterized constructor
    public Student(String name, int xp) {
        this.name = name;
        this.xp = xp;
    }

    // Overloaded constructor with default XP
    public Student(String name) {
        this(name, 0); // Constructor chaining
    }

    public void awardXp(int points) {
        this.xp += points;
        System.out.println(this.name + " now has " + this.xp + " XP!");
    }
}
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What is the purpose of the `this` keyword inside a Java constructor or instance method?