Home Java Java Constructor

Java Constructor

In Java, a constructor is a particular method for initializing objects. When a class object is formed, the constructor is called. It’s possible to use it to set the default values for object attributes as follows:

// Creating the Main class in Java
public class JavaConstructor {
  String a;

  // Creating a class constructor for the Main class
  public JavaConstructor() {
    a = "I am the constructor";
  }

  public static void main(String[] args) {
    JavaConstructor objInstance = new JavaConstructor();
    System.out.println(objInstance.a);
  }
}

It’s worth noting that the constructor name must be the same as the class name, and it can’t have a return type (like void). In addition, when an object is created, the constructor is invoked. By default, all classes have constructors; if you don’t create one yourself, Java will do so for you. However, you will be unable to specify initial values for object properties in this case.

Parameters for constructors

Constructors can also accept arguments, which are used to set up attributes. The constructor is extended with an int a parameter in the example below. We set a to b (a=b) inside the constructor. We supply an argument of (10) to the constructor when we call it, and it sets the value of to 10:

public class JavaConstructor {
  int a;

  public JavaConstructor(int b) {
    a = b;
  }

  public static void main(String[] args) {
    JavaConstructor objInstance;= new JavaConstructor(10);
    System.out.println(objInstance.a);
  }
}

You are free to use as many parameters as you like:

//filename: JavaConstructor.java
public class JavaConstructor {
  int modelYear;
  String modelName;

  public JavaConstructor(int year, String name) {
    modelYear = year;
    modelName = name;
  }

  public static void main(String[] args) {
    JavaConstructor myCar = new JavaConstructor(2020, "Sedan");
    System.out.println(myCar.modelYear + " " + myCar.modelName);
  }
}

Rules govern the constructor in Java. These rules for writing a Java constructor are as follows:

  • The constructor’s name must match the class’s name.
  • There must be no explicit return type in a constructor.
  • An abstract, static, final, and synchronized Java constructor is impossible.

Types of constructors in Java

Java constructors come in a variety of shapes and sizes. In Java, there are two types of constructors:

  • A default Constructor (no-arg constructor)
  • Constructor with parameters

Default Constructor in Java

When a constructor has no parameters, it is called the “Default Constructor.” The default constructor has the following syntax:

<class_name>(){}  

Example: Default constructor

The no-arg constructor of the defaultConstructor class is created in this example. It will be called when the object is created.

//Program creating and calling a default constructor  
class defaultConstructor{  

//creating a default constructor  
defaultConstructor(){
System.out.println("This is the default constructor");

}  
//main method  
public static void main(String args[]){  
//calling a default constructor  
defaultConstructor b=new defaultConstructor();  
}  
}  

If a class doesn’t have a constructor, the compiler adds one automatically.

What is a default constructor’s purpose?

The default constructor gives the object default values like 0, null, and so on, depending on the type. A default constructor that displays the default settings is an example.

// default constructor  example
// show the default values  
class Employee{  
int id;  
String firstName;  
String lastName;  

//method to display the value of id and name  
void display(){System.out.println(id+" "+firstName+" "+lastName);}  
  
public static void main(String args[]){  
// object creation  

Employee empOne=new Employee();  
Employee empTwo=new Employee();  

//displaying values of the object  
empOne.display();  
empTwo.display();  
}  
}  

The compiler created one for us because we didn’t make a constructor in the above class. The default constructor provides 0 and null values in this case.

Constructor with Parameters in Java

A parameterized constructor is a constructor that has a set number of parameters. Why would you want to use a parameterized constructor? Different values are assigned to other objects using the parameterized constructor. You can, however, provide the same values.

Example: A parameterized constructor

We’ve developed a constructor for the Employee class with two parameters in this example. The constructor can contain any number of parameters.

//Program demonstrating the use of the parameterized constructor.  
class Employee{  
    int id;  
    String firstName;  
    String lastName;  

    //creation of a parameterized constructor  
    Employee(int i,String fname, String lname){  
    id = i;  
    firstName;   = fname;  
    lastName;    = lname;
	
    }  

    //method to display the values  
    void display(){System.out.println(id+" "+firstName+" "+lastName);}  
   
    public static void main(String args[]){  

    //creating objects and passing values  
    Employee empOne = new Employee(20,"Thomas","Keen");  
    Employee empTwo = new Employee(30,"Ann","Thompson");  

    //calling method to display the values of object  
    empOne.display();  
    empTwo.display();  
   }  
}

Java Constructor Overloading

A constructor is similar to a method in Java, except it does not have a return type. Just like Java methods, it can be overloaded.

In Java, constructor overloading refers to multiple constructors with varying parameter lists. They’re structured so that each constructor does something distinct. The compiler distinguishes them based on the number of parameters in the list and their kinds.

Example: Overloading of a Constructor in Java

//Program illustrating constructor overloading

class Employee{  
    int id;  
    String firstName;  
    String lastName;  
    int age;
  
    //creation of a two arg constructor  
    Employee(int i,String fname){  
    id = i;  
    firstName = fname;  
    }  
    //creation of a three arg constructor  
    Employee(int i,String fname, String lname){  
    id = i;  
    firstName = fname;  
    lastName = lname;
    }  

  //creation of a four arg constructor  
    Employee(int i,String fname, String lname,int a){  
    id = i;  
    firstName = fname;  
    lastName = lname;
    age=a;  
    }  



    void display(){System.out.println(id+" "+name+" "+age);}  
   
    public static void main(String args[]){  
    Employee empOne = new Employee(20,"Ann");  
    Employee empTwo = new Employee(30,"Thomas","Saks");  
    Employee empThree = new Employee(40,"Jerry","Floyd", 49);  

    empOne.display();  
    empTwo.display();  
    empThree.display();
   }  
}  

Constructor for Copying in Java

In Java, there is no copy constructor. However, using the copy constructor in C++, we can copy values from one object to another. In Java, there are numerous methods for copying the values of one object to another. They are as follows:

  • Using constructor
  • By transferring the values of one object to another, you can create a new one.
  • Using the Object class’s clone() function

In this example, we’ll use the Java constructor to replicate the values of one object to another.

// program for  initializing the values from one object to another object.  
class Employee{  
    int id;  
    String firstName;  
    //constructor for initializing an integer and string  
    Employee(int i,String fname){  
    id = i;  
    firstName = fname;  
    }  
    //constructor to initialize another object  
    Employee(Employee empOne){  
    id = empOne.id;  
    firstName =empOne.firstName;  
    }  
    void display(){System.out.println(id+" "+firstName);}  
   
    public static void main(String args[]){  
    Employee empOne = new Employee(20,"Ann");  
    Employee empTwo = new Employee(empOne);  
    empOne.display();  
    empOne.display();  
   }  
}  

Conclusion

The Constructor class in Java is used to access the internal information of a class’s constructor. The constructor can do other things other than initializing, such as creating an object, initiating a thread, or calling a method. In the constructor, you can execute any operation in the method. The java.lang.reflect package contains it.

A constructor in Java is a block of code comparable to a method. When a new class instance is created, this method is invoked. Memory for the object is allocated when the constructor is called.

It’s a specific kind of method that’s used to set up an object. At least one constructor is invoked every time an object is created with the new() keyword. In this scenario, the Java compiler automatically creates a default constructor. If no constructor is available in the class, it uses the default constructor. There are two types of constructors in Java: no-arg and parameterized constructors.

You may also like

Leave a Comment