Constructor in Java

Constructor in java is a special type of method. And constructor are used to initialize data members of the objects.

  • It has same name as its class name.
  • It does not have any explicit return.(implicitly it returns current class instance)
  • It is implicitly invoked at the time of object creation.

Rule for creating Java constructor

  • Constructor name must be same as its class name
  • Constructor must have no explicit return type

Types of Constructor

There are two types of constructor in java

  • default Constructor(Constructor with no argument)
  • Parameterized Constructor

type of constructor

If there is no constructor in a class ,compiler automatically creates a default constructor.

Java default Constructor

A Constructor,Define with no parameter is known as Default constructor

Syntax

  class_Name ()
   { 
					  
   } 

Example


Rectangle r=new Rectangle (5, 7);

 

If a class does not contain any constructors then default constructor(Constructor without parameters) is provided the compiler at the time of the compilation but if a class contains parameterized constructor and any object of the class required default than it need to be provided by the class itself in such a case compiler don’t provide default constructor.


Example Of Default Constructor

we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation.

class Car {
	Car() {
		System.out.println(" Car running ");
	}

	public static void main(String args[]) {
		Car b = new Car();
	}

} 
 

Q - What is the purpose of default constructor?

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

Example of default constructor that displays the default values

class Collage {
	int id;
	String name;

	void display() {
		System.out.println(id + " " + name);
	}

	public static void main(String args[]) {
		Collagec1 = new Collage();
		Collagec2 = new Collage();
		c1.display();
		c2.display();

	}

}
  Output:0 null
   0 null
       

Important Point of Constructor -

In the above class,you are not creating any constructor so compiler provides you a default constructor.Here 0 and null values are provided by default constructor.


Java Parameterized Constructors

A Constructor, defined with parameter is known as Parameterized Constructor.

Why use parameterized constructor?

Parameterized constructor is used to afford different values to the distinct objects

Example

 class Collage {
	int id;
	String name;

	Collage(int i, String n) {
		id = i;

		name = n;
	}

	void display() {
		System.out.println(id + " " + name);
	}

	public static void main(String args[]) {
		Collagec1 = new Collage(111, "SMU");
		Collages2 = new Collage(222, "PTU");

		c1.display();
		c2.display();
	}

}

	 
 111 SMU
 222 PTU
 

Constructor Overloading in Java

Constructor overloading is a performance in Java in which a class can have any number of constructors that differ in parameter lists. The compiler differentiates these constructors by taking into account the number of parameters in the list and their type.

Example

 class Student {

	int id;
	String name;
	int age;

	Student(int i, String n) {
		id = i;
		name = n;
	}

	Student(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[]) {
		Student s1 = new Student(111, "Mithilesh");
		Student s2 = new Student(222, "Rahul", 25);
		s1.display();
		s2.display();
	}
}
111 Mithilesh 0
222 Rahul  25

Difference between constructor and method in java

Java Constructor Java Method
Constructor is used to initialize state of an object. methods. 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 complier 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..

Q - Does constructor return any value?

Ans :yes, that is current class instance (You cannot use return type yet it returns a value). Example to understand Default and Parameterized Constructor

class Rectangle {
	int length, breadth;

	public Rectangle()// default Constructor
	{
		length = 5;
		breadth = 6;
	}

	public Rectangle(int l, int b)// parameterized Constructor
	{
		length = l;
		breadth = b;
	}

	public void display() {
		System.out.println("length is : " + length);
		System.out.println("breadth is : " + breadth);
	}

	public static void main(String ar[]) {
		Rectangle r1 = new Rectangle();// invoking default constructor
		r1.display();
		Rectangle r2 = new Rectangle(3, 4);// invoking parameterized constructor
		r2.display();
	}

}

length is  : 5
breadth is : 6
length is  : 3
breadth is : 4

Copy Constructor in Java


Like C++, Java also supports copy constructor. But then again, different C++, Java doesn't create a default copy constructor if you don't write your private.

Following is an example of copy constructor.

					
class Complex {
 
    private double re, im;
     
    // A normal parametrized constructor 
    public Complex(double re, double im) {
        this.re = re;
        this.im = im;
    }
     
    // copy constructor
    Complex(Complex c) {
        System.out.println("Copy constructor called");
        re = c.re;
        im = c.im;
    }
      
    // Overriding the toString of Object class
    @Override
    public String toString() {
        return "(" + re + " + " + im + "i)";
    }
}
 
public class Main {
 
    public static void main(String[] args) {
        Complex c1 = new Complex(10, 15);
         
        // Following involves a copy constructor call
        Complex c2 = new Complex(c1);   
 
        // Note that following doesn't involve a copy constructor call as 
        // non-primitive variables are just references.
        Complex c3 = c2;   
 
        System.out.println(c2); // toString() of c2 is called here
    }
}

Output

	
Copy constructor called
(10.0 + 15.0i)