Constructor in Java with Example


  • In Java, a constructor is a member function of a class. 
  • The name of the constructor is the same as the name of the class like see below.
  • class Hello{
    	//constructor
    	Hello(){
    		//constructor body.
    	}
    }
    
  • It has no return type, so we can't use the return keyword.
  • It must be an instance member function, that is, it can never be static.
  • All the classes have a default constructor in Java.
  • When there is no constructor defined in the class by the programmer, the compiler implicitly provides a default constructor for the class.
  • A constructor can be parameterized.
  • A constructor can be overloaded.


When is a constructor called? 

Whenever we are creating an instance of the class using the new keyword by default a constructor is called implicitly known as default constructor. It initializes the newly created object. For example, in this case, we make an object of class MyClass using the new keyword.

class MyClass{
	MyClass(){
		//constructor body.
	}
	public static void main(String args[]){
		MyClass obj = new MyClass(); //instance created using new keyword.
	}
}


Rules for creating a constructor:

  • The constructor name and class name must be the same.
  • A constructor cannot have any return type.
  • It can never be static, abstract, and final.

Types of constructor in Java:

There are two types of constructor in Java.
1. Default (no-argument) constructor.
2. Parameterized constructor.


1. Default Constructor in Java:

When there is no constructor defined in the class by the programmer, the java compiler implicitly provides a default constructor for the class. This constructor is known as the default constructor in java. It doesn't accept any parameter. If we create any constructor in our class then java compiler doesn't create any constructor in our class.


Example of Default Constructor:


class Test{
	int a;
	int b;
	//constructor creation.
	Test(){
		System.out.println("We are inside default constructor");
		a= 10;
		b = 20;
	}
	public void display(){
		System.out.println("Value of a is: " +a);
		System.out.println("Value of b is: " +b);
	}
}
class ConstructorDemo{
	public static void main(String args[]){
		Test obj = new Test();
		obj.display();
	}
}

Output:

We are inside default constructor.
Value of a is: 10
Value of b is: 20


2. Parameterized Constructor in Java:

A constructor that accepts one or more parameters is known as a parameterized constructor. Whenever we have to create an object of the class that has a parameterized constructor, we need to pass the arguments so that this constructor gets invoked after the creation of an object.


Example of Parameterized Constructor:

In this example, we are going to show you how to calculate an area of a Rectangle using a parameterized constructor. Here we have created the constructor of Rectangle class that has two parameters (length, and width).

class Rectangle{
	int length;
	int width;
	int result;
	
	//parameterized constructor
	Rectangle(int l, int w){
		length = l;
		width = w;
	}
	
	//calculate the area of rectangle.
	public void rectArea(){
		result = length*width;
		System.out.println("Area of rectangle is: " +result);
	}
}
class ConstructorDemo{
	public static void main(String args[]){
		//passing the values to constructor.
		Rectangle obj = new Rectangle(10, 20);
		obj.rectArea();
	}
}

Output:

Area of rectangle is: 200


Constructor Overloading in Java:

Constructor overloading is just like method overloading. When more than one constructor is defined in a class with a different parameter list, then it is called constructor overloading in java or the use of multiple constructors in a class. In constructor overloading, every constructor performs a different task.

Example of Constructor Overloading in Java:


class Student{
	int rollno;
	String name;
	int age;
	
	//constructor with one argument.
	Student(int r){
		rollno = r;
	}
	
	//constructor with two arguments.
	Student(int r, String n){
		rollno = r;
		name = n;
	}
	
	//constructor with three arguments.
	Student(int r, String n, int a){
		rollno = r;
		name = n;
		age = a;
	}
	//display rollno, name, and age.
	public void display(){
		System.out.println(rollno+ " " +name+" " +age);
	}
}
class ConstructorDemo{
	public static void main(String args[]){
		//passing the value in the constructor.
		Student obj1 = new Student(101);
		Student obj2 = new Student(101, "Prashant");
		Student obj3 = new Student(101, "Prashant", 21);
		obj1.display();
		obj2.display();
		obj3.display();
		
	}
}

Output:

101 0
101 Prashant 0
101 Prashant 21


Constructor Chaining in Java:

  • A constructor can call other constructors of the same class or superclass. 
  • Constructor call from a constructor must be the first step (call should appear in the first line).
  • The first line of the constructor is either super() or this() (by default super()). 
  • super() keyword calls the superclass constructor.
  • this() keyword calls the same class constructor.
  • Such a series of invocation of constructors is known as Constructor Chaining in Java.
  • Constructor never contains super(), and this() both.
  • It contains either super(), or this().
  • The process of constructor chaining can be achieved through inheritance.



Example of Constructor chaining in java:


class Person{
	public Person(){
		System.out.println("This is person class constrcutor");
	}
}
class Student extends Person{
	public Student(){
		this("Amit");
		System.out.println("This is student class constrcutor");
	}
	public Student(String name){
		System.out.println("Student name is Amit");
	}
}
class ConstructorDemo{
	public static void main(String args[]){
		Student obj = new Student();
	}
}

Output:

This is person class constructor
Student name is Amit
This is student class constructor

Understand the flow of execution of a Constructor chaining example. It will help you to understand how constructor chaining works. Let's see in below fig.

Constructor in Java


Java Copy Constructor:

Copy Constructor is a constructor that is used to create a copy of an already existing object of the same class. It takes a single argument whose type is that of the class containing constructor. Unlike C++, there is no copy constructor in java. But we can copy the value of one object into another in java by a constructor, assigning the value of one object into another, and by object cloning (clone() method of object class).




Example of Java Copy Constructor:

In this example, we are going to show you how we can copy the value of one object into another object using java constructor

class Employee{
 int id;
 String name;
 
 //constructor to initialize integer and string 
 Employee(int i, String n){
  id = i;
  name = n;
 }

 //constructor to initialize another object  
 Employee(Employee s){
  id = s.id;
  name = s.name;
 }
 void display(){
  System.out.println(id + " " + name);
 }
 public static void main(String args[]){
  Employee e1 = new Employee(101, "Prashant");
  Employee e2 = new Employee(e1);
  e1.display();
  e2.display();
 }
}

Output:

101 Prashant
101 Prashant



You may also like the related posts:


Constructor in Java with Example Constructor in Java with Example Reviewed by Prashant Srivastava on December 31, 2018 Rating: 5

No comments:

Powered by Blogger.