Constructors in Java

Constructors are used to initialize an object, during object creation of a particular java class. Constructors are called during object creation.

Important points about constructors:

  • Constructors are not considered as members of a Java class.
  • Constructors does not have any return type.
  • Name of the constructor should be same as class name.

Following is the basic format of a constructor:

public ClassName(param-list) [throws exception...]{
//Initialization code here

Here public keyword is access modifier, which makes the constructor accessible to other classes. (We can use private to prevent constructor access from outside of the class). Constructors also can have parameters passed to it. Constructors also may throw exceptions if it contains code, which may throw any kind of exception.

Following is the simple example of Car class:

public class Car {
private String model;
private int speed;
//Constructor without parameters:
public Car() {
   model = "Car Model";
   speed = 120;
//Constructor with model and speed parameters:  
public Car(String model, int speed) {
   String model = this.model;
   int speed = this.speed;

If we do not declare any constructor for a class compiler calls no-argument, default constructor and all instance variables of the class is set with default value(i.e, a int variable with 0, and so on..).

We can have more than one constructor for a class as shown above, with each constructor having different argument list.

Also Read: