Constructor in Java

Constructor is a special type of a method which is called every time an object is created.

Constructor is used to initialize a value to the variables at the time of creation of object.

The name of the constructor should be same as the class name and should not contain any return type as in normal methods.

Syntax for creating object,

new Class_name();

class_name() is the constructor above. Every time when a new object is created, a method of class name is called which is known as constructor.

Two types of constructor

  • Default constructor
  • Parameterized constructor

Default constructor

This is the method with no parameters and return type.

General Syntax

Class_name(){

}

Example

class ConstructorTest2{

int data;

ConstructorTest2(){ //default constructor

data=2;

}

public static void main(String args[]){

ConstructorTest2 ct=new ConstructorTest2();

System.out.println("Default value of variable 'data' "+ct.data);

}

}

Try In Editor

Output

Default value of variable 'data' 2


Constructor is automatically created when no constructor is defined.

It assigns default values to the variables of a specific object.

Example

class ConstructorTest{

int data;

public static void main(String args[]){

ConstructorTest ct=new ConstructorTest();

System.out.println("Default value of variable 'data' "+ct.data);

}

}

Try In Editor

Output

Default value of variable 'data' 0


Parameterized constructor

Constructor with parameters is known as parameterized constructor.

General Syntax

Class_name(parameter(s)){

}

Example 1

class ParamConstructorTest{

int data;

ParamConstructorTest(int value){ //Parameterized constructor

data=value;

}

public static void main(String args[]){

ParamConstructorTest ct=new ParamConstructorTest(5);

System.out.println("Default value of variable 'data' "+ct.data);

}

}

Try In Editor

Output

Default value of variable 'data' 5


Example 2

class ParamConstructorTest2{

int data;

float seconds;

ParamConstructorTest2(int value,float sec){

data=value;

seconds=sec;

}

public static void main(String args[]){

ParamConstructorTest2 ct=new ParamConstructorTest2(5,1.2f);

System.out.println("Default value of variable 'seconds' "+ct.seconds);

}

}

Try In Editor

Output

Default value of variable 'seconds' 1.2


Related topics

What is OOPs in Java ?