DEV Community

Cover image for Constructor in Java
PRIYA K
PRIYA K

Posted on

Constructor in Java

A special method used to initialise objects.
Constructor is a block of code similar to method
Constructor is called when an object of a class is created

All Classes have constructors by 'default'
Java (JDK) creates a Class Constructor ,you need not to create a Class constructor
Accept parameters to initialise Object properties
It is used to set default or user-defined values for the object's attributes
Initialise objects at the time of object creation.

Constructor Syntax

class ClassName {
    // Constructor
    ClassName() {
        // Initialization code
    }

    // Parameterized Constructor
    ClassName(dataType parameter1, dataType parameter2) {
        // Initialization code using parameters
    }

    // Copy Constructor
    ClassName(ClassName obj) {
        // Initialization code to copy attributes
    }
}
Enter fullscreen mode Exit fullscreen mode

Example

class Bike{
    Bike(){
        System.out.println("Bike is created");
    }
    public static void main(String[]args){
        Bike b = new Bike();

    }

}

Enter fullscreen mode Exit fullscreen mode

Output

Rules For Creating Constructor
1.Name Rule
Constructor name must match the Class name
2.Return Type Rule
It cannot have a return type (like void) or explicit return type
if you add a return type,it will become a method not a return type
3.Execution Rule
A constructor is called as per the object creation(New)
4.Default Constructor Rule
No constructor is defined, Java provides a default no-arg constructor.
you can define any constructor, the default is not automatically provided.
5.Access Modifiers Rule
A constructor have modifiers like Private,Public,Protected or default
Private Constructore have used in singleton Design Pattern
to be discussed...
6.Restrictions Rule
A constructor cannot be

  • static(Belong to Class,not Objects) because Constructor is called using Objects.static is called by class
  • final(Not Inherited)
  • abstract(must have a body)
  • and synchronised to be discussed...

7.Inheritance Rule
Constructor not inherited by SubClass
Call a Parent Constructor using Super()

8.this() and super() Rule
A constructor can call another constructor in the same class using this().
A constructor can call a parent’s constructor using super().
In Java ≤ 24 → must be the first statement.
In Java 25 → can appear anywhere in the constructor.

Types Of Constructor

  • Default Constructor
  • Parameterised Constructor
  • No-argument Constructor

Default Constructor (Implicit)
A constructor doesnot have any parameter
Doesnot defined any constructor
They Initialise Object with Default Values
A constructor that is automatically provided by Java if no constructor is written in the class.
It initializes object with default values (0, null, false).

Example
It is called when the object of the class is created

class Bike {
    int id;
    String name;

    void display() {
        System.out.println(id + " " + name);
    }

    public static void main(String[] args) {
        Bike b = new Bike();   // calls default constructor
        b.display();
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Purpose Of Default Constructor
Provide Default values to the object like 0,null.depending on their data type.

No-Argument Constructor(User-defined)
user-defined empty constructor
A constructor that is manually written by the programmer with no parameters.
It is used to initialize objects with custom default values.

class Bike {
    int id;
    String name;

    // No-argument constructor
    Bike() {
        id = 101;
        name = "Duke";
    }

    void display() {
        System.out.println(id + " " + name);
    }

    public static void main(String[] args) {
        Bike b = new Bike();
        b.display();
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Parameterised Constructor(Explicit)
A constructor have a any number of parameter
Used to provide different value for objects
Accepts arguments to initialize an object with specific values.
It allows passing values while creating the object.

class Bike {
    int id;
    String name;

    // Constructor only initializes values
    Bike(int id, String name) {
        this.id = id;
        this.name = name;
    }

    // Method to display bike details
    void display() {
        System.out.println(id + " " + name);
    }

    public static void main(String[] args) {
        Bike b = new Bike(111, "Duke");
        Bike p = new Bike(122, "Splender");

        b.display();
        p.display();
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Constructor OverLoading
Allows to create multiple constructors in the same class with different parameter and different data type
It can be overloaded like Java Methods
You can define all type of Constructors like no-argument and parameterised constructor.

Example

class Bike {
    int id;
    String name;

    // 1. Constructor with no parameters
    Bike() {
        id = 0;
        name = "Null";
    }

    // 2. Constructor with one parameter
    Bike(int id) {
        this.id = id;
        this.name = "Default Bike";
    }

    // 3. Constructor with two parameters
    Bike(int id, String name) {
        this.id = id;
        this.name = name;
    }

    void display() {
        System.out.println(id + " " + name);
    }

    public static void main(String[] args) {
        Bike b1 = new Bike();              // calls 1st constructor
        Bike b2 = new Bike(111);           // calls 2nd constructor
        Bike b3 = new Bike(122, "Duke");   // calls 3rd constructor

        b1.display();
        b2.display();
        b3.display();
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

What is this() in java 25 Upadte
It is used to call another Constructor with the same class(Constructor Chaining)
The restriction this() and super() used as first statement in constructor is removed.
Place them anywhere inside a constructor
this() and super()=>they enable clean and flexible initialization.

Copy Constructor
A constructor that creates a new object by copying values from an existing object of the same class.
It is used to duplicate objects.

class Bike {
    int id;
    String name;

    Bike(int id, String name) {
        this.id = id;
        this.name = name;
    }

    // Copy constructor
    Bike(Bike b) {
        this.id = b.id;
        this.name = b.name;
    }

    void display() {
        System.out.println(id + " " + name);
    }

    public static void main(String[] args) {
        Bike b1 = new Bike(111, "Duke");

        Bike b2 = new Bike(b1);  // copy constructor

        b1.display();
        b2.display();
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Do You Know?
1.this Keyword (Avoid confusion)
Used when class variable and parameter have same name
this refers to current class constructor
this refers to current object
this() calls another constructor in the same class .This technique is called Constructor Chaining

Example:

class Bike {
    int id;
    String name;

    Bike(int id, String name) {
        this.id = id;      // class variable = parameter
        this.name = name;
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation
this.id → object’s variable
id → constructor parameter

Without this, Java gets confused

2.Constructor Chaining (this())

One constructor calling another constructor
Simple idea:
“Reuse constructor instead of writing same code again”

Example:

class Bike {
    int id;
    String name;

    Bike() {
        this(0, "Unknown");  // calls another constructor
    }

    Bike(int id, String name) {
        this.id = id;
        this.name = name;
    }
}
Enter fullscreen mode Exit fullscreen mode

Bike() → calls Bike(int, String)
Saves duplicate code

3.Immutable Object (Fixed data)

Once object is created, you cannot change its values
Means
“Lock the object after creation "

Example:

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

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

    public String getName() {
        return name;
    }
}
Enter fullscreen mode Exit fullscreen mode

final → cannot change value
No setter methods → data is fixed

4. Exception Handling in Constructor
Handle errors while creating object
stop invalid object creation

Means
“If object is wrong, stop it immediately”

Example:

class Student {
    int age;
    Student(int age) {
        if (age < 0) {
            throw new Illegal ArgumentException("Age cannot be negative");
        }
        this.age = age;
    }
}
Enter fullscreen mode Exit fullscreen mode

If invalid data comes → constructor blocks it
Object is created only if data is correct

Top comments (0)