Thuta Learning
IntermediateProgrammingbeginner

Constructors

Relax. We'll talk through this in plain words — no textbook voice.

A constructor is a special method that gets called automatically when you create an object. It's most often used to initialize field values as the object is being built. A constructor's name has to match the class name, and it has no return type.

java
class Course {
  String title;
  int lessons;

  Course(String courseTitle, int lessonCount) {
    title = courseTitle;
    lessons = lessonCount;
  }

  void showInfo() {
    System.out.println(title + " has " + lessons + " lessons.");
  }
}

public class Main {
  public static void main(String[] args) {
    Course javaCourse = new Course("Java Basics", 12);
    javaCourse.showInfo();
  }
}

new Course("Java Basics", 12) calls the constructor and sets the title and lessons. Once the object is built, showInfo() prints out the data.

You should see
Java Basics has 12 lessons.

Real-World Use

The constructor pattern shows up when setting a username/email while creating a user account, or setting a name/price while creating a product.

Easy traps

  • Writing a constructor like a regular method — void Course() — is a mistake. That turns it into a normal method instead of a constructor.
Constructors | Thuta Learning