DEV Community

Cover image for Constructor in Java
PRIYA K
PRIYA K

Posted on • Edited on

Constructor in Java

read gfg
w3schools constructor,this,super keyword
tutorialpoint
programmiz

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.

It can be used to set initial values for object attributes:

A constructor in Java is a special member that is called when an object is created. It initializes the new object’s state. It is used to set default or user-defined values for the object's attributes
A constructor has the same name as the class.
It does not have a return type, not even void.
It can accept parameters to initialize object properties.

is syntactically similar to a method. However, constructors have no explicit return type.

Typically, you will use a constructor to give initial values to the instance variables defined by the class or to perform any other start-up procedures required to create a fully formed object.

A constructor in Java is a special block of code used to initialize a newly created object. It is automatically invoked when you instantiate an object using the new keyword.

Accept parameters to initialise Object properties
Initialise objects at the time of object creation.

All classes have constructors, whether you define one or not because Java automatically provides a default constructor that initializes all member variables to zero. However, once you define your constructor, the default constructor is no longer used.

All Classes have constructors by 'default'
Java (JDK) creates a Class Constructor ,you need not to create a Class constructor.
. However, then you are not able to set initial values for object attributes.

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.
Java provides a default constructor that is invoked during the time of object creation. If you create any type of constructor, the default constructor (provided by Java) is not invoked.

5.Access Modifiers Rule
The access modifiers can be used with the constructors, use if you want to change the visibility/accessibility of constructors.A constructor have modifiers like Private,Public,Protected or default
Private Constructor 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
  • not final(Not Inherited)
  • not abstract(must have a body)
  • and not 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.

Key Rules for Creating Constructors
Automatic Call: It runs once per object lifecycle at the time of creation.
Forbidden Modifiers: It cannot be declared as static, abstract, or final

Important Notes on Java Constructors
Constructors are invoked implicitly when you instantiate objects.
The two rules for creating a constructor are:
1. The name of the constructor should be the same as the class.
2. A Java constructor must not have a return type.
If a class doesn't have a constructor, the Java compiler automatically creates a default constructor during run-time. The default constructor initializes instance variables with default values. For example, the int variable will be initialized to 0

**Constructor types:**
No-Arg Constructor - a constructor that does not accept any arguments
Parameterized constructor - a constructor that accepts arguments
Default Constructor - a constructor that is automatically created by the Java compiler if it is not explicitly defined.
A constructor cannot be abstract or static or final.
A constructor can be overloaded but can not be overridden.
Enter fullscreen mode Exit fullscreen mode

Creating a Java Constructor
To create a constructor in Java, simply write the constructor's name (that is the same as the class name) followed by the brackets and then write the constructor's body inside the curly braces ({}).

Syntax

class ClassName {
   ClassName() {
   }
}
Enter fullscreen mode Exit fullscreen mode

Java this Keyword
The this keyword in Java refers to the current object in a method or constructor.
The this keyword is often used to avoid confusion when class attributes have the same name as method or constructor parameters.

When to use this?
When a constructor or method has a parameter with the same name as a class variable, use this to update the class variable correctly.
To call another constructor in the same class and reuse code.

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.

Accessing Class Attributes
Sometimes a constructor or method has a parameter with the same name as a class variable. When this happens, the parameter temporarily hides the class variable inside that method or constructor.

To refer to the class variable and not the parameter, you can use the this keyword.

Calling a Constructor from Another Constructor
You can also use this() to call another constructor in the same class.
This is useful when you want to provide default values or reuse initialization code instead of repeating it.

Note: The call to this() must be the first statement inside the constructor.

Java super Keyword
In Java, the super keyword is used to refer to the parent class of a subclass.
The most common use of the super keyword is to eliminate the confusion between superclasses and subclasses that have methods with the same name.

It can be used in two main ways:
To access attributes and methods from the parent class
To call the parent class constructor

Access Parent Methods
If a subclass has a method with the same name as one in its parent class, you can use super to call the parent version.

Note: Use super when you want to call a method from the parent class that has been overridden in the child class.
Access Parent Attributes

You can also use super to access an attribute from the parent class if they have an attribute with the same name.

Call Parent Constructor
Use super() to call the constructor of the parent class. This is especially useful for reusing initialization code.
Note: The call to super() must be the first statement in the subclass constructor.

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

Constructor Parameters
Constructors can also take parameters, which is used to initialize attributes.

Types Of Constructor

  • Default Constructor
  • Parameterised Constructor
  • No-argument Constructor

Default Constructor (Implicit)
A constructor doesnot have any parameter
Doesnot defined any constructor
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).
It’s used to assign default values to an object. If no constructor is explicitly defined, Java provides a default constructor.
If you do not create any constructor in the class, Hence, the Java compiler automatically creates the default constructor.Java provides a default constructor that initializes the object.
there is no constructor defined by us. The default constructor is there to initialize the object.

 Note: It is not necessary to write a constructor for a class because the Java compiler automatically creates a default constructor (a constructor with no arguments) if your class doesn’t have any. 
Enter fullscreen mode Exit fullscreen mode

constructor.
The default constructor initializes any uninitialized instance variables with default values.

Type Default Value
boolean false
byte 0
short 0
int 0
long 0L
char \u0000
float 0.0f
double 0.0d
object Reference null

If we do not create any constructor, the Java compiler automatically creates a no-arg constructor during the execution of the program.
This constructor is called the default constructor

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.
As the name specifies, the No-argument constructor does not accept any argument. By using the No-Args constructor you can initialize the class data members and perform various activities that you want on object creation.
Similar to methods, a Java constructor may or may not have any parameters (arguments).
If a constructor does not accept any parameters, it is known as a no-argument constructor. For example,

private Constructor() {
   // body of the constructor
}
Enter fullscreen mode Exit fullscreen mode

Notice that we have declared the constructor as private.
Once a constructor is declared private, it cannot be accessed from outside the class.
So, creating objects from outside the class is prohibited using the private constructor.
Here, we are creating the object inside the same class.
Hence, the program is able to access the constructor

However, if we want to create objects outside the class, then we need to declare the constructor as public.

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.
A constructor that has parameters is known as parameterized constructor. If we want to initialize fields of the class with our own values, then use a parameterized constructor.
A constructor with one or more arguments is called a parameterized constructor.
A Java constructor can also accept one or more parameters. Such constructors are known as parameterized constructors (constructors with parameters).
Parameters are added to a constructor in the same way that they are added to a method, just declare them inside the parentheses after the constructor's name.

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

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.
Unlike other constructors copy constructor is passed with another object which copies the data available from the passed object to the newly created object.
Note: Java does not provide a built-in copy constructor like C++. We can create our own by writing a constructor that takes an object of the same class as a parameter and copies its fields.

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

Private Constructor
A private constructor cannot be accessed from outside the class. It is commonly used in:
Singleton Pattern: To ensure only one instance of a class is created.
Utility/Helper Classes: To prevent instantiation of a class containing only static methods.

class GFG {
    // Private constructor
    private GFG(){
        System.out.println("Private constructor called");
    }
    // Static method
    public static void displayMessage(){
        System.out.println("Hello from GFG class!");
    }
}
class Main{
    public static void main(String[] args){
        // GFG u = new GFG(); // Error: constructor is
        // private
       GFG.displayMessage();
    }
}
Enter fullscreen mode Exit fullscreen mode

Output
Hello from GFG class!

Constructor Overloading in Java
Constructor overloading means multiple constructors in a class. When you have multiple constructors with different parameters listed, then it will be known as constructor overloading.

Similar to Java method overloading, we can also create two or more constructors with different parameters. This is called constructor overloading.

Based on the parameter passed during object creation, different constructors are called, and different values are assigned.
It is also possible to call one constructor from another constructor.

Note: We have used this keyword to specify the variable of the class.

Java Program to implement private constructors
Example 1: Java program to create a private constructor

class Test {
  // create private constructor
  private Test () {
    System.out.println("This is a private constructor.");
  }

  // create a public static method
  public static void instanceMethod() {
    // create an instance of Test class
    Test obj = new Test();
  }

}

class Main {
  public static void main(String[] args) {
    // call the instanceMethod()
    Test.instanceMethod();
  }
}
Enter fullscreen mode Exit fullscreen mode

Output

This is a private constructor.

In the above example, we have created a private constructor of the Test class. Hence, we cannot create an object of the Test class outside of the class.

This is why we have created a public static method named instanceMethod() inside the class that is used to create an object of the Test class. And from the Main class, we call the method using the class name.

Example 2: Java Singleton design using a private constructor

The Java Singleton design pattern ensures that there should be only one instance of a class. To achieve this we use the private constructor.

class Language {

// create a public static variable of class type
private static Language language;

// private constructor
private Language() {
System.out.println("Inside Private Constructor");
}

// public static method
public static Language getInstance() {

 // create object if it's not already created
 if(language == null) {
    language = new Language();
 }

  // returns the singleton object
  return language;
Enter fullscreen mode Exit fullscreen mode

}

public void display() {
System.out.println("Singleton Pattern is achieved");
}
}

class Main {
public static void main(String[] args) {
Language db1;

 // call the getInstance method
 db1= Language.getInstance();

 db1.display();
Enter fullscreen mode Exit fullscreen mode

}
}

Run Code

Output

Inside Private Constructor
Singleton Pattern is achieved

In the above example, we have created a class named Languages. The class contains,

language - class type private variable
Language() - private constructor
getInstance() - public static class type method
display() - public method
Enter fullscreen mode Exit fullscreen mode

Since the constructor is private, we cannot create objects of Language from the outer class. Hence, we have created an object of the class inside the getInstance() method.

However, we have set the condition in such a way that only one object is created. And, the method returns the object.

Notice the line,

db1 = Language.getInstance();

Here,

db1 is a variable of Language type
Language.getInstance() - calls the method getInstance()
Enter fullscreen mode Exit fullscreen mode

Since, getInstance() returns the object of the Language class, the db1 variable is assigned with the returned object.

Finally, we have called the display() method using the object.

Top comments (0)