Java Constructors

Java Constructors

A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes.


Creating a Constructor

A constructor must have the exact same name as the class, and it cannot have a return type (like void or int).

Simple Constructor Example

public class Main {
  int x;

// This is the constructor for the Main class public Main() { x = 5; // Set the initial value for the class attribute x }

public static void main(String[] args) { Main myObj = new Main(); // Create an object of class Main (this will call the constructor) System.out.println(myObj.x); // Print the value of x } }

Note: All classes have constructors by default. If you do not create a class constructor yourself, Java creates one for you. However, you are not able to see it. The default constructor is an empty constructor that doesn't assign any values.


Constructor Parameters

Constructors can also take parameters, which are used to initialize attributes. This is the most common way to create objects with specific initial states.

Constructor with Parameters

public class Car {
  String modelName;
  int modelYear;

// Constructor with parameters public Car(String name, int year) { modelName = name; modelYear = year; }

public static void main(String[] args) { Car myCar = new Car("Mustang", 1969); System.out.println("My car is a " + myCar.modelYear + " " + myCar.modelName); } }

Constructors save you a lot of time, as they help you to initialize an object's attributes with just one line of code.