Understanding Constructors in Java

Welcome! In this lesson, we will be exploring Java's constructor, a key element in object creation. Imagine creating cars on an assembly line, each painted a particular color, assigned an engine number, and further personalized, just like an object in Java. Today, we'll decipher constructors, which are essential to Java.

A constructor in Java is a specific method that initializes objects. It shares the same name as the class and doesn't return any type. If there are no user-defined constructors, Java provides a default one.

The Syntax of Constructors

Constructors in Java adhere to some specific rules. The name of a constructor must be the same as the class name. Like a method, a constructor has a body enclosed between curly braces { }. A constructor looks like this:

Java
public class Dog {
  
  String breed; // Attribute 1
  int age; // Attribute 2
  
  // Dog class constructor
  Dog(String breed, int age) {
    this.breed = breed; // Initialize attribute 1
    this.age = age; // Initialize attribute 2
    System.out.println("Initialized Dog class with breed=" + this.breed + " and age=" + this.age);
  } 
}

In this example, Dog is a constructor, taking two parameters - a String breed and an int age. The this keyword refers to the current instance. So this.breed refers to the breed attribute of the current dog object, and similarly for age.

How to Use Constructors

Constructors help us instantiate a class or create an object from a class. They set initial values for object attributes and carry out other functions that are necessary to create the object. Once a constructor is defined, it is automatically called when an object is created.

Here is an example of creating a Dog object, fido from the Dog class using a constructor.

public class Solution {
  public static void main(String[] args) {

    // Create 'fido' using the Dog class constructor
    Dog fido = new Dog("Alsatian", 5); // Prints: Initialized Dog class with breed=Alsatian and age=5
    
    System.out.println(fido.breed);  // prints: Alsatian
    System.out.println(fido.age);  // prints: 5
  }
}

The expression Dog fido = new Dog("Alsatian", 5); follows the format Class object = new Class(args);, which creates the fido object. It also prints the statement we left in the constructor in the previous section, showing the constructor has actually been called.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal