Java Constructors: Initializing Objects with Special Methods

Discover the role of constructors in Java, which are special methods used to initialize objects when they are created. Constructors can set initial values for object attributes, ensuring that your objects are properly configured from the moment of instantiation. Learn about the different types of constructors and how they enhance object-oriented programming in Java, providing a foundation for creating robust applications.



Java Constructors

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

Syntax

// Create a Main class
public class Main {
int x;  // Create a class attribute

// Create a class 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
}
}

// Outputs 5
Output

5

Note: The constructor name must match the class name, and it cannot have a return type (like void). All classes have a default constructor if you do not create one.

Constructor Parameters

Constructors can take parameters to initialize attributes. For example:

Syntax

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);
}
}

// Outputs 5
Output

5

You can have multiple parameters in a constructor:

Syntax

public class Main {
int modelYear;
String modelName;

public Main(int year, String name) {
modelYear = year;
modelName = name;
}

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

// Outputs 1969 Mustang
Output

1969 Mustang