Constructor in Java

A constructor in Java is a block of code similar to a method that’s called when an instance of an object is created. Here are the key differences between a constructor and a method.

  • A constructor doesn’t have a return type.

  • The name of the constructor must be the same as the name of the class.

  • Unlike methods, constructors are not considered members of a class.

  • A constructor is called automatically when a new instance of an object is created.

When is a constructor called

Everytime an object is created using new() keyword, atleast one constructor is called. It is called a default constructor.

Note: It is called constructor because it constructs the values at the time of object creation. It is not necessary to write a constructor for a class. It is because java compiler creates a default constructor if your class doesn't have any.

Types of java constructors

There are two types of constructors in java:

  1. Default constructor (no-arg constructor)
  2. Parameterized constructor
Default constructor in Java

Are no-arg constructor and default constructor same?

This is a confusing question for some as you may find different answers to this question from different sources. Some of you will not agree with me but as per my understanding they are different. The default constructor is inserted by compiler and has no code in it, on the other hand we can implement no-arg constructor in our class which looks like default constructor but we can provide any initialization code in it.

Like C++, Java automatically creates default constructor if there is no default or parameterized constructor written by user, and (like C++) the default constructor automatically calls parent default constructor. But unlike C++, default constructor in Java initializes member data variable to default values (numeric values are initialized as 0, booleans are initialized as false and references are initialized as null).

Syntax of default constructor:
<class_name>(){}
// Main.java class Test { int i; Test t; boolean b; byte bt; float ft; } public class Main { public static void main(String args[]) { Test t = new Test(); // default constructor is called. System.out.println(t.i); System.out.println(t.t); System.out.println(t.b); System.out.println(t.bt); System.out.println(t.ft); } }


Output:
0 null false 0 0.0
Default Constructor Example
class NoteBook{ /*This is default constructor. A constructor does * not have a return type and it's name * should exactly match with class name */ NoteBook(){ System.out.println("Default constructor"); } public void mymethod() { System.out.println("Void method of the class"); } public static void main(String args[]){ /* new keyword creates the object of the class * and invokes constructor to initialize object */ NoteBook obj = new NoteBook(); obj.mymethod(); } }


Output:
Default constructor Void method of the class
What is the purpose of default constructor?

Default constructor is used to provide the default values to the object like 0, null etc. depending on the type.

Example of default constructor that displays the default values
class Student3{ int id; String name; void display(){System.out.println(id+" "+name);} public static void main(String args[]){ Student3 s1=new Student3(); Student3 s2=new Student3(); s1.display(); s2.display(); } }


Output:
0 null 0 null
Java parameterized constructor

A Constructor which has parameters in it called as Parameterized Constructors, this constructor is used to assign different values for the different objects. In the below example we have a constructor for the Car class which takes in the the value and sets to the property, lets try to set the value for the property “carColor”

Example
public class Car { String carColor; Car(String carColor) { this.carColor = carColor; } public void disp() { System.out.println("Color of the Car is : "+carColor); } public static void main(String args[]) { //Calling the parameterized constructor Car c = new Car("Blue"); c.disp(); } }


Output:
Color of the Car is : Blue
Another Example of parameterized constructor

we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor.

class Student4{ int id; String name; Student4(int i,String n){ id = i; name = n; } void display(){System.out.println(id+" "+name);} public static void main(String args[]){ Student4 s1 = new Student4(31,"Pavi"); Student4 s2 = new Student4(36,"Rama"); s1.display(); s2.display(); } }


Output:
31 Pavi 36 Rama
Can i have a class with No Constructor ? What will happen during object creation ?

Yes, we can have a class with no constructor, during the time of object creation the compiler will create a default constructor for you automatically.

public class Car { public void disp() { System.out.println("disp() method of the Car class called"); } public static void main(String args[]) { //Calling the No argument constructor Car c1 = new Car(); c1.disp(); } }


Output:
disp() method of the Car class called

In the above code we haven’t declared the default constructor, yet we have created a object and called the disp() method over it. This is possible only because the compiler has created the default constructor for you.

Does compiler create Default constructor everytime ?
public class Car { String carColor; Car(String carColor) { this.carColor = carColor; } public void disp() { System.out.println("Color of the Car is : "+carColor); } public static void main(String args[]) { //Calling the No argument constructor Car c1 = new Car(); //Calling the parameterized constructor Car c2 = new Car("Blue"); c2.disp(); } }


Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: The constructor Car() is undefined at com.javainterviewpoint.Car.main(Car.java:18)
Constructor Overloading in Java

In Java, a constructor is just like a method but without return type. It can also be overloaded like Java methods.

Constructor overloading in Java is a technique of having more than one constructor with different parameter lists. They are arranged in a way that each constructor performs a different task. They are differentiated by the compiler by the number of parameters in the list and their types.

Example:
class Student5{ int id; String name; int age; Student5(int i,String n){ id = i; name = n; } Student5(int i,String n,int a){ id = i; name = n; age=a; } void display(){System.out.println(id+" "+name+" "+age);} public static void main(String args[]){ Student5 s1 = new Student5(31,"Pavi"); Student5 s2 = new Student5(36,"Rama",35); s1.display(); s2.display(); }


Output:
31 Pavi 0 36 Rama 35
Difference between constructor and method in java
Java ConstructorJava Method
Constructor is used to initialize the state of an object.Method is used to expose behaviour of an object.
Constructor must not have return type.Method must have return type.
Constructor is invoked implicitly.Method is invoked explicitly.
The java compiler provides a default constructor if you don't have any constructor.Method is not provided by compiler in any case.
Constructor name must be same as the class name. Method name may or may not be same as class name.
Java-Copy Constructors

There is no copy constructor in java. But, we can copy the values of one object to another like copy constructor in C++.

There are many ways to copy the values of one object into another in java. They are:

  • By constructor
  • By assigning the values of one object into another
  • By clone() method of Object class
class Student6{ int id; String name; Student6(int i,String n){ id = i; name = n; } Student6(Student6 s){ id = s.id; name =s.name; } void display(){System.out.println(id+" "+name);} public static void main(String args[]){ Student6 s1 = new Student6(31,"Rama"); Student6 s2 = new Student6(s1); s1.display(); s2.display(); } }


Output:
31 Rama 31 Rama

Sometimes, we may wish to prepare a duplicate of an existing object of a class. In such situations, we have to use a special type of constructor, known as copy constructor. This constructor can take only one parameter, which is a reference to an object of the same class. In the following program, the class Data contains two variables data1 and data2, a constructor, a copy constructor and the method showData( ) to display the data1 and data2 values. Within the main( ) method of the Javaapp class, the object d1 of class Data is created by using the usual constructor. One more object of a class Data is created by using copy constructor, which takes d1 as its only argument.

class Data{ int data1; int data2; Data(int d1, int d2) { data1 = d1; data2 = d2; } Data(Data obj) { data1 = obj.data1; data2 = obj.data2; } void showData() { System.out.println("Data1 :"+data1); System.out.println("Data2 :"+data2); } } public class Javaapp { public static void main(String[] args) { Data d1 = new Data(20,40); d1.showData(); Data d2 = new Data(d1); d2.showData(); } }


Output:
Data1 :20 data2 :40 Data1 :20 data2 :40
Copying values without constructor

We can copy the values of one object into another by assigning the objects values to another object. In this case, there is no need to create the constructor.

class Student7{ int id; String name; Student7(int i,String n){ id = i; name = n; } Student7(){} void display(){System.out.println(id+" "+name);} public static void main(String args[]){ Student7 s1 = new Student7(31,"Rama"); Student7 s2 = new Student7(); s2.id=s1.id; s2.name=s1.name; s1.display(); s2.display(); } }


Output:
31 Rama 31 Rama



Instagram