Java Constructors

java

In Java, a constructor is a special type of method that is used to create and initialize an object. Every class has at least one constructor, and a class can have multiple constructors with different parameter lists.

The syntax for defining a constructor is similar to that of a method, but the name of the constructor must be the same as the name of the class. A constructor does not have a return type, not even void.

Here is an example of a class with a constructor:

public class Person {
  private String name;
  private int age;

  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }

  // Getters and setters for the name and age attributes
}

In this example, the Person class has a constructor with two parameters: name and age. The constructor initializes the name and age attributes of the Person object with the values of the parameters.

To create a new object of the Person class, you can use the new operator and call the constructor, like this:

Person person = new Person("John", 30);

This will create a new Person object with the name “John” and age 30.

If a class does not have a explicit constructor, the Java compiler will automatically create a default constructor for the class. The default constructor has no parameters and does not perform any initialization.