Java Constructor

What is a Constructor?

A constructor is a function found within a class that is in charge of setting up an objects initial state. Whenever an object is made the constructor gets called automatically to reserve memory for the object and set its attributes. Constructors are vital, in object oriented programming as they ensure that objects are correctly configured and ready to be utilized. They establish the starting values of member variables call methods when needed and offer a convenient means to assign default values or carry out any necessary setup tasks. Constructors have the name as the class they belong to and do not specify a return type. They can be overloaded, allowing different versions of the constructor to be used based on the needs of object initialization.

Purpose of Constructors in Java

In Java constructors are methods that are used to set up object variables when the object is created. They play a role in ensuring that objects are properly configured and ready for use. When an object is instantiated using the "keyword a constructor is automatically called to initialize the objects state by assigning values to its variables. This initialization step ensures that the object starts off in an consistent state right from the beginning.

Constructors have the name as the class they belong to and do not return any value. They can be overloaded, allowing developers to create constructors with different parameters. This flexibility enables ways of initializing object variables based on varying requirements.

By utilizing constructors developers can guarantee that essential variables are initialized with initial values thus preventing unexpected issues or errors. This initialization process is crucial, for ensuring that objects operate correctly and reliably within a program.

How Constructors are Different from Methods

In Java programming, constructors and methods play roles in object oriented programming each serving distinct functions, with notable variations.

Purpose

In programming constructors are used to set up objects of a class while methods are responsible for executing functions or operations, within that class.

Invocation

  • Constructors: Automatically invoked when an object is created.
  • Methods: Explicitly called to perform various operations on objects.

Return Type

  • Constructors: Do not have a return type, not even void.
  • Methods: Must have a return type, which can be void or a specific data type.

Default Constructor

In Java the compiler creates a default constructor when no specific constructor is defined. However if there is at one explicit constructor defined the default constructor will not be automatically generated.

Types of Constructors in Java

Default Constructor

  • Provided by Java if no other constructors are explicitly defined.
  • Has no parameters and initializes the object with default values.

Parameterized Constructor

  • Takes one or more parameters and allows the programmer to set the initial values of the object's instance variables.
  • Can be overloaded to provide different sets of parameters for object initialization.

Copy Constructor

When you want to make an object that mirrors the current state of another object you can do so by passing an object from the same class, as a parameter. This way the new object will be set up with the values as the instance variables of the existing object.

Default Constructor

In Java, a default constructor is automatically created if no constructor is explicitly defined within a class. It is a constructor that takes no arguments and performs the basic initialization of the object. It is often used when the initialization logic is not complex and does not require any parameters.

A no-argument constructor, on the other hand, is a constructor that takes no arguments but is explicitly defined within a class. It can have its implementation and perform additional initialization beyond the default initialization performed by the default constructor.

Example

public class Tree {
    private String type;
    private int height;

    // Default constructor
    public Tree() {
        type = "Unknown";
        height = 0;
    }

    // Other constructors and methods

    public static void main(String[] args) {
        Tree oakTree = new Tree(); // Creating an instance using the default constructor
        System.out.println(oakTree.getType()); // Output: Unknown
        System.out.println(oakTree.getHeight()); // Output: 0
    }
}

In this example, the default constructor of the Tree class initializes the instance variables type and height to their default values.

No-Argument Constructor

In Java a default constructor, which is also referred to as a no argument constructor doesn't require any parameters. It is utilized to instantiate an object of a class without supplying any values to its attributes or variables.

If there is no constructor defined in a Java class the compiler automatically inserts a default constructor. This default constructor sets the objects variables to their default values. Null for reference types and 0 for numeric types.

Moreover, developers can define a no argument constructor within a class to have control, over how the object is initialized. By creating a custom no argument constructor developers can establish default values or perform additional tasks before using the object.

Parameterized Constructor

A parameterized constructor is a kind of constructor that accepts one or more parameters allowing values to be assigned to objects, during their creation.

Example

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

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

    // Getter methods and other code...
}

To create a Student object using the parameterized constructor and assign values, we can write:

Student student = new Student("John", 20);

Copy Constructor

When working with a copy constructor in Java it's important to create a constructor that accepts an object, from the class itself as a parameter. This specific constructor will then proceed to duplicate the data from the provided object into the instantiated object.

Example

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

    // Copy constructor
    public Person(Person otherPerson) {
        this.name = otherPerson.name;
        this.age = otherPerson.age;
    }

    // Other constructors and methods
}

Apart from using a copy constructor, other ways to copy the values of one object into another include assignment statements or the clone() method.

Private Constructor

A private constructor is declared using the private keyword. It restricts object creation within a class, meaning instances of the class can only be created from within the class itself.

Usage Scenarios

  • Singleton Classes: A class that allows only one instance of itself to be created.
  • Utility Classes: Classes containing only static methods and should not be instantiated.

Syntax and Declaration of Constructors in Java

Syntax of a Constructor

  1. Access Modifier: Specifies the visibility (public, protected, private, or package-private).
  2. Class Name: The constructor has the same name as the class.
  3. Parameters: Optional; allows passing values to initialize instance variables.
  4. Body: Contains statements that are executed when the constructor is called, enclosed within curly braces {}.

Declaring a Constructor in a Class

To declare a constructor, start by declaring it within the class definition. Constructors do not have a return type, not even void. They have the same name as the class and are declared with an access modifier like public, private, or protected.

Example

public class MyClass {
    private String name;

    // Constructor
    public MyClass(String name) {
        this.name = name;
    }
}

Rules for Defining Constructors in Java

  • Constructors must have the same name as the class.
  • Constructors do not have a return type.
  • A class can have multiple constructors (constructor overloading).
  • Constructors can have access modifiers (public, private, protected).
  • If a custom constructor is defined, the default constructor is not automatically invoked.

Characteristics of Constructors in Java

  • Initialization: Responsible for initializing objects and setting their initial values.
  • Overloading: Can be overloaded to provide flexibility in object creation.
  • Implicit Invocation: Automatically called when an object is created.
  • No Return Type: Constructors do not return any value.

Create a free account to access the full topic

“It has all the necessary theory, lots of practice, and projects of different levels. I haven't skipped any of the 3000+ coding exercises.”
Andrei Maftei
Hyperskill Graduate