← Chapter 6 — Object-Oriented Programming

24. Constructors & this Keyword

mixed

Description

A constructor runs when an object is created. It initializes the object so it begins in a valid, useful state.

The this keyword refers to the current object. It is commonly used to distinguish a field from a parameter with the same name.

Subtopics

Constructor parameters

Description

Constructors can accept initial values.

Explanation

Their name matches the class and they have no return type.

Example

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

Using this

Description

this refers to the current object.

Explanation

this.name selects the field instead of the parameter.

Example

this.score = score;

Explanation

If you write any constructor, Java no longer creates the no-argument constructor automatically. Add one explicitly only when your design needs it.

Example

public class ConstructorDemo {
    static class Student {
        String name;
        int score;
        Student(String name, int score) {
            this.name = name;
            this.score = score;
        }
    }

    public static void main(String[] args) {
        Student aditi = new Student("Aditi", 92);
        System.out.println(aditi.name);
    }
}

Key points

  • Constructors initialize objects.
  • Constructor names match the class.
  • this refers to the current object.

Open reference