Java ยท Chapter 23 of 42

Java Constructors

A constructor is a special method used to initialize a new object, sharing the same name as its class and having no return type. It runs automatically when an object is created with new.

If you don't define any constructor, Java provides a default no-argument constructor automatically. You can also overload constructors to allow different ways of creating objects.

Syntax
class C {
  C() { }
  C(int x) { }
}

Default vs parameterized constructors

A default constructor takes no arguments; a parameterized constructor accepts arguments to set initial field values at creation time.

Constructor overloading

A class can have multiple constructors with different parameter lists, giving flexible ways to create objects.

Example 1 (java)
class Car {
  String brand;
  Car(String brand) {
    this.brand = brand;
  }
}
public class Main {
  public static void main(String[] args) {
    Car myCar = new Car("Honda");
    System.out.println(myCar.brand);
  }
}
Output
Honda

The constructor sets the brand field using the argument passed to new Car("Honda").

Key points

  • A constructor shares its class's name and has no return type.
  • Java provides a default no-arg constructor if none is defined.
  • Constructors can be overloaded for flexible object creation.
  • this refers to the current object inside a constructor.
๐Ÿ’ก Note: Once you define any constructor, Java no longer auto-generates the default one.

๐Ÿ“ Quick Quiz

1. What is a constructor's return type?

2. What does `this.brand = brand` do?

3. When is the default constructor still generated?