- Need of Constructor
- SYNTAX TO DEFINE A CONSTRUCTOR:
- Example:
- INVOKING A CONSTRUCTOR
- Example:
- When is a Constructor called?
- Rules you should have in mind while using a constructor:
- Features of a constructor:
- Types of constructor
- Super()
- Constructor Overloading
- How are constructors different from methods in Java?
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 them. This is where a constructor comes in. A constructor is defined with the same name as the class. 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 variables 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 variables 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 introduced constructors to simplify object initialization. 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 a default constructor in Java itself.
Learn Java the right way! Our course teaches you essential programming skills, from coding basics to complex projects, setting you up for success in the tech industry.
SYNTAX TO DEFINE A CONSTRUCTOR:
class <class name>{
dataMember1;
dataMember2;
dataMember3;
...............
dataMembern;
<class name>(){
dataMember1 = value;
dataMember2 = value;
dataMember3 = value;
..................
dataMembern = value;
}
Example:
class Item{
int a;
float b;
char c;
String s;
Item() { // 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:
<ClassName> objectName = new ClassName();
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{
// A Constructor
new GreatLearning() {}
}
// 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:
- Constructors of a class should have the same name as the class name.
- A constructor cannot be abstract, final, static, or synchronized.
- 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:
- 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 nameItem
. Hence, it is a constructor. - The constructor is only used to initialize the data members and instance variables.
- 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.
Example:
Item ob = new Item(); // This calls the constructor Item()
- 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.
- 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 constructors find their application in the singleton design patterns.
- 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:
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. If we define any constructor (parameterized or not), the compiler does not generate 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.
void display(){
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(String[] args){
GL ob = new GL(); // Calling default Constructor
ob.display();
}
}
Output:
Initial value of c is
Initial value of a is 0
Initial value of l is 0
Initial value of f is 0.0
Initial value of d is 0.0
Initial value of s is null
Note: Initial value for a character variable is ”. 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
0
Non-parameterized constructor:
A constructor which initializes the instance variables 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:
- Created by the compiler
- Created by the programmer
(i)Created by the compiler:
//to illustrate non parameterized constructor
class n_const{
int a,b;
// Non-parameterized constructor
n_const() {
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;
// Non-parameterized constructor
n_const() {
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(String[] args){
n_const ob = new n_const();
ob.display();
}
}
In the program above n_const()
is the non-parameterized constructor.
Output:
The value of a is 5.
The value of b is 8.
Parameterized Constructor:
Constructors that take 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 the concept of a “copy constructor”, though it does not provide one by default. 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, 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 passed to 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 invoked, it implicitly invokes the constructor of the parent class. The compiler automatically 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. The compiler distinguishes constructors based on the number 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 class 'GL'
// 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 are constructors different from methods in Java?
- Constructors must have the same name as the class within which they are defined, while it is not necessary for methods in Java.
- Constructors do not have a return type, while methods have a return type or void if they do not return any value.
- A constructor is called only once at the time of Object creation, while method(s) can be called any number of times.