Lesson 29 +10 XP

Java Constructors

A constructor is a special method that runs when an object is created. It usually sets the initial values of the object.

Constructor syntax

A constructor has the same name as the class and no return type:


java
public class Main {
  int x;

public Main() {
    x = 5;
  }

public static void main(String[] args) {

### Main myObj = new Main();

### System.out.println(myObj.x); // 5
  }
}

Constructor with parameters


java
public class Main {
  int x;

public Main(int y) {
    x = y;
  }

public static void main(String[] args) {

### Main myObj = new Main(5);

### System.out.println(myObj.x); // 5
  }
}

Constructors can be overloaded

Like methods, constructors can have different parameter lists so you can create objects in different ways.

Key facts

  • The constructor name matches the class name.
  • It has no return type, not even void.
  • It runs automatically when you use new.

TL;DR

  • A constructor runs when an object is created.
  • It shares the class name and has no return type.
  • Use parameters to set initial values.