Monday, December 31, 2018

Constructor in Java

The name of the constructor is the same as the name of the class like see below.

class Hello

{

Hello() // Constructor

{

// methods.

}

}

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()

{

// methods.

}

public static void main(String args [])

{

MyClass obj = newMyClass(); // instance created using new keyword.

}

}

Rules for creating a constructor:

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;

Test()

{

System.out.println(" We are inside default constructor! ");

a=10;

b=20;

}

public void display()

{

System.out.println("Value of the first number is: " +a);

System.out.println("Value of the second number is: " +b);

}

}

class ConstructorDemo

{

public static void main(String args [])

{

Test obj = new Test();

obj.display();

}

}

Output:

We are inside default constructor!

Value of the first number is 10.

Value of the second number is 20.

2. Parameterized Constructor in Java:

A constructor that accepts one or more parameter is known as a parameterized constructor. Whenever we have to create an object of the class that has parameterized constructor, we need to pass the arguments so that this constructor gets invoked after creation 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 have two parameters (length, and width).

class Rectangle

{

int length;

int width;

int result;

Rectangle(int x,int y)

{

length = x;

width = y;

}

public void rectArea()

{

result = length * width;

System.out.println(" Area of a rectangle is: " +result);

}

}

class ConstructorDemo

{

public static void main(String args [])

{

Rectangle obj = new Rectangle(10,20);

obj.rectArea();

}

}

Output:

Area of a 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 different parameter list, then it is called constructor overloading in java or 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;

// creating one-arg constructor

Student(int r)

{

rollno = r;

}

// creating two-arg constructor

Student(int r, String n)

{

rollno = r;

name = n;

}

// creating three-arg constructor

Student(int r, String n, int a)

{

rollno = r;

name = n;

age = a;

}

public void dispaly()

{

System.out.println(rollno+" "+name+" "+age);

}

}

class ConstructorDemo

{

public static void main(String args [])

{

// invoke the constructor with one-arg.

Student obj1 = new Student(101);

// invoke the constructor with two-arg.

Student obj2 = new Student(101, "Rahul");

// invoke the constructor with three-arg.

Student obj3 = new Student(101, "Rahul", 21);

obj1.display();

obj2.dispaly();

obj3.display();

}

}

Output:

101 null 0

101 Rahul 0

101 Rahul 21

Constructor Chaining in Java:

A constructor can call others 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 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 constructor");

}

}

class Student extends Person

{

public Student()

{

this("Amit");

System.out.println("This is student class constructor");

}

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 Constructor chaining example. It will help you to understand how constructor chaining work. Let's see in below fig.

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.