Browse by Domains

Constructors in Java

What is a constructor? 

We all know that an object of a particular class contains instance variables, but if we want to perform some operations on the instance variables we need to initialize the Instance variables. This is where a constructor comes in. You can do so by having the same name as the class name. Such a method is called a constructor. 

Hence, a constructor is a method having the same name as that of the class and is used to initialize the instance variable of the objects. 

Need of Constructor 

When you make various objects of a class, data members are automatically allocated under each object. If you are allowed to initialize data members at the time of declaration in class then the data members corresponding to all the objects will possess the same initial values. But in practice, you would want to have different initial values for the instance variable of the objects and in case you use any member method to initialize the data members you may have to call it separately every time after creating an object. The creators of java have thus given us a boon by creating a concept called constructors. Hence, practically, you require such a member method that can automatically be called while creating an object to initialize its elements. To do so you need a CONSTRUCTOR. So let us dive deep into the constructors used in Java.

So, constructors are used to allocating values to the class variables during object creation, which is either explicitly done by the developer/programmer or by default constructor in Java itself. 

Also Read: Data Structures and Algorithm in Java

SYNTAX TO DEFINE A CONSTRUCTOR:

class <class name> 
{ 
<data member 1> 
<data member 2> 
<data member 3> 
............... 
<data member n> 
<class name>() 
{ 
<data member 1=value> 
<data member 2=value> 
<data member 3=value> 
.................. 
<data member n=value> 
} 

Example:

class Item 
{ 
int a; 
float b; 
char c; 
String s; 
Item() // Member method with the same name as the constructor {
a=0; 
b=0.0; 
c=’’; //Initializing instance variables 
s=”””; 
}

INVOKING A CONSTRUCTOR 

A constructor is invoked at the time of creating an object of the class. The syntax of Invoking a constructor is: 

<class name><object name>=new <class name()> 

Example:


Item ob=new Item(); 

Here, 

Item is the class name. 

Ob represents an object. 

new is a keyword or operator. 

Item() is calling the constructor. (In this case, it’s a default constructor) 

When is a Constructor called? 

Whenever an object is created using a new() keyword, a constructor (could be a default constructor) is invoked to assign initial values to the data members of the same class. 

A constructor is invoked during object or instance creation. For Example: 

class GreatLearning 

X x x x x x 

// A Constructor 

new GreatLearning() {} 

x x x x x x x

// We can create an object of the above class 

// using the below statement. This statement 

// calls above constructor. 

GreatLearning obj = new GreatLearning(); 

Rules you should have in mind while using a constructor: 

● Constructor/s of a class should have the same name as the class name. and 

● A constructor can not be abstract, final, static and Synchronized. and 

● Access modifiers can be used in constructor declaration to control its access i.e which other class can call the constructor. 

Features of a constructor: 

1)The constructor is defined with the same name as that of the class. Concerning the above example, The method Item() has the same name as the class name Item. Hence It is a constructor. 2)The constructor is only used to Initialize the data members and Instance variables 

3)The constructor is automatically called while creating an object. When an object is created, the constructor gets called implicitly. You need not call the constructor through the object like other member methods. 

Eg:Item ob=new Item();Calling the constructor Item() 4)The constructor needs no return type. 

A constructor is used only to initialize the data members. No arithmetic or logical operation is performed in a constructor. Hence, the return type of the constructor is not at all required.

5)The constructor can be public, private as well as protected. A constructor is always called from outside the class while creating an object. Hence, the access specifier of the constructor by default is public, but we can also declare the constructor as private or protected but we would not be able to create the object of the class. private constructor finds their application in the singleton design patterns. 

6)The constructor is overloaded automatically. 

Several constructors created for a class are automatically overloaded as they will possess the same name as the class name and will contain different types of parameters. 

Types of constructor 

There are four different types of constructors in Java:

1. Default constructor: A constructor used to initialize the instance variables with the default values is called a default constructor. A constructor that contains no parameter is known as the default constructor. The compiler creates a default constructor for the class if we do not do it by ourselves. And if we write a constructor with arguments or no-arguments then the compiler does not create a default constructor. Whenever no constructor is defined in a program, the compiler creates a constructor of its own. Whenever an object of a particular class is created, it uses this constructor to initialize the instance variables with the default values. 

// Java Program to illustrate calling a 
// no-argument constructor 
import java.io.*;
class GL 
{ 
Char c;int a;long l; float f; double d;String S; 
// this would be invoked while an object 
// of that class is created. 
voiddisplay() 
{ 
System. out. Println ("Initial value of c is" +c); 
System. out. Println ("Initial value of a is" +a); 
System. out. Println ("Initial value of l is" +l); 
System. out. Println ("Initial value of f is" +f); 
System. out. Println ("Initial value of d is" +d); 
System. out. Println ("Initial value of S is" +S); 
} 
public static void main() 
{ 
GL ob = new GL(); -> Calling default Constructor 
Ob.display(); 
} 
}

Output: 

The initial value of c is 

The initial value of a is 0 

The initial value of l is 0 

The initial value of f is 0.0 

The initial value of d is 0.0 

The initial value of s is null 

Note: Initial value for a character variable is ‘\u0000’. It represents a null character. Hence, the initial value of c is not displayed in the BlueJ terminal Window(As shown above).

class GL 
{ 
public static void main (String[] args) 
{ 
// this would invoke the default constructor. 
GL gL1 = new GL(); 
// Default constructor provides the default 
// values to the object like 0, null 
System.out.println(gL1.name); 
System.out.println(gL1.num); 
} 
} 

Output : 

Constructor called 

null 

2. Non-parameterized constructor: 

A constructor which initializes the instance variable of an object with definite values readily available within it is known as a Non parameterized constructor. A non-parameterized constructor is defined with the constructor name along with the empty parameter list. (i.e n_pconst()) 

Objects can be created in two ways : 

1)Created by the compiler 

2)Created by the programmer 

(i)Created by the compiler: 

//to illustrate non parameterized constructor 
class n_const 
{
int a,b; 
n_const() - --Non parameterized constructor { 
a=5; 
b=8; 
} 
void display() 
{ 
System. Out. Println(“The value of a is “+a); System. Out. Println(“The value of b is “+b); } 
}

Output: 

The value of a is 5. 

The value of b is 8. 

(ii)Object created by the programmers:

//to illustrate non parameterized constructor class n_const 
{ 
int a,b; 
n_const() - --Non parameterized constructor { 
a=5; 
b=8; 
} 
void display() 
{ 
System. Out. Println(“The value of a is “+a); System. Out. Println(“The value of b is “+b); }
public static void main() 
{ 
n_const ob= new n_const(); 
ob.display(); 
} 

In the program above n_const() is the parameterized constructor. Output: 

The value of a is 5. 

The value of b is 8.

3.Parameterized Constructor: Constructors that can take at arguments as input are termed parameterized constructors. As soon as an object is declared in a parameterized constructor, the initial values are passed as arguments to the constructor. The normal way may not work. The constructors can be called explicitly and also implicitly. If we call the method explicitly it is also called a shorthand function.

// Java Program to illustrate calling of 
// parameterized constructor. 
import java.io.*; 
class GL 
{ 
// data members of the class. 
String name; 
int id;
// constructor would initialize data members 
// with the values of passed arguments while 
// object of that class created. 
GL(String name, int id) 
{ 
this.name = name; 
this.id = id; 
} 
} 
class GFG 
{ 
public static void main (String[] args) 
{ 
// this would invoke the parameterized constructor. 
GL GL1 = new GL("adam", 1); 
System.out.println("GLName :" + GL1.name + 
" and GLId :" + GL1.id); 
} 
} 

Output: 

GLName :adam and GLId :1 

Can constructors return any value? 

There are no “return value” types of statements in the constructor, but the constructor can return the current class instance. We can write ‘return’ inside a constructor. 

(iv)Copy constructors: Java supports “Copy Constructor” which defines the actions performed by the compiler when copying class objects But, Java doesn’t create a default copy constructor. It has one formal parameter that is the type of the class (the parameter may be

a reference to an object), used to create a copy of an existing object of the same class. Even though both the classes are the same, it counts as a conversion constructor. The copy constructors we use in java abbreviated copy ctor or cctor, they have nothing to do with class constructors used in .NET using the same abbreviation. Copy constructors are of two types: 

1)Direct entry copy constructor: 

The initial value of an object is copied by assigning it to another object. 

Eg: 

class copy_con 
{ 
//class using parameterized copy constructors 
int a,b; 
copy_con(int x,int y) 
{ 
a=x ; 
b=y ; 
} 
} 
class abc 
{ 
public static void main(String[] args) 
{ 
copy_con ob=new copy_con(5,8); 
copy_con ob1=ob; 
} 
} 

(ii)Copy constructor by passing object 

In this system, the object is passed to the constructor. Further, the instance variables of the current object(i.e the object through which

the constructor is called) are initialized by copying the values from the objects passed to the constructor. 

class copycon 
{ 
//class using parameterized and copy constructor 
Int a,b; 
copycon(int x,int y) 
{ 
a=x ; 
b=y ; 
} 
copycon(copycon p) //copy constructor 
{ 
a=p.a ; 
b=p.b ; 
} 
} 
class abc 
{ 
public static void main(String args[]) 
{ 
copycon ob=new copycon(5,8); 
copycon ob1=new copycon(ob); 
} 
} 

copycon ob=new copycon(5,8) initializes the instance variables a and b of the object ob with 5 and 8(with parameterized constructor). 

When object ob1 is created, the object ob is referred to pin the constructor copycon(copycon p) which in turn transfers the initial values of ob to the variables a and b of the object ob1 respectively.

Super() 

Whenever a child class constructor gets/is invoked, it implicitly invokes the constructor of the parent class. You can say that the compiler inserts a super(); statement at the beginning of the child class constructor. 

class MyParentClass { 
MyParentClass(){ 
System.out.println("MyParentClass Constructor"); 
} 
} 
class MyChildClass extends MyParentClass{ 
MyChildClass() { 
System.out.println("MyChildClass Constructor"); 
} 
public static void main(String args[]) { 
new MyChildClass(); 
} 
} 

Output: 

MyParentClass Constructor 

MyChildClass Constructor 

Constructor Overloading 

Like methods, we can overload the constructors for creating objects in different ways. Compiler distinguishes constructors based on numbers of parameters, types of the parameters, and order of the parameters.

// Java Program to illustrate constructor overloading // using same task (addition operation ) for different // types of arguments. 
import java.io.*; 
class GL 
{ 
// constructor with one argument 
GL(String name) 
{ 
System.out.println("Constructor with one " + 
"argument - String : " + name); 
} 
// constructor with two arguments 
GL(String name, int age) 
{ 
System.out.println("Constructor with two arguments : " + " String and Integer : " + name + " "+ age); 
} 
// Constructor with one argument but with a different // type than previous... 
GL(long id) 
{ 
System.out.println("Constructor with an argument : " + "Long : " + id); 
} 
}
class GFG 
{ 
public static void main(String[] args) 
{ 
// Creating the objects of the class named 'Geek' 
// by passing different arguments 
// Invoke the constructor with one argument of 
// type 'String'. 
GL GL2 = new GL("Shikhar"); 
// Invoke the constructor with two arguments 
GL GL3 = new GL("Dharmesh", 26); 
// Invoke the constructor with one argument of 
// type 'Long'. 
GL GL4 = new GL(325614567); 
} 
} 

Output: 

Constructor with one single argument – String: Shikhar Constructor with two arguments – String and Integer: Dharmesh 26 Constructor with one argument – Long: 325614567

How constructors are different from methods in Java? 

● Constructor(s) must and should have the same name as the class within which it is defined while it is not necessary for the method in java. 

● Constructor(s) does not return any return type while method(s) have the return type or void if does not return any value. ● Constructor is called only once at the time of Object creation while method(s) can be called any number of times.

Avatar photo
Great Learning Team
Great Learning's Blog covers the latest developments and innovations in technology that can be leveraged to build rewarding careers. You'll find career guides, tech tutorials and industry news to keep yourself updated with the fast-changing world of tech and business.

Leave a Comment

Your email address will not be published. Required fields are marked *

Great Learning Free Online Courses
Scroll to Top