Constructor is a type of method which is used to initialize the object that called at the time of object creation.
To create constructor, constructor name should be same as class name and also does not use explicit return type in case of constructor.
 
Types of Java Constructors
There are two types of java constructors:

  1. Default constructor
  2. Parameterized constructor

 
1. Default constructor – A constructor which have no parameter is known as default constructor.
Syntax

<class_name>(){
}

Example

public class Addition
{
Addition()  // default constructor
{
System.out.println("Addition Constructor");
}
public static void main(String args[]){
Addition ad=new Addition (); // Automatically default constructor is called
}
}

Output
Addition Constructor
 
2. Parameterized Constructor – A constructor which contains parameters is known as parameterized constructor.
Syntax

<class_name>(Parameter_list){
}

Example

public class Addition
{
int c;
Addition(int a, int b)  // parameterized constructor
{
c = a + b;
System.out.println("Addition of two numbers:"+c);
}
public static void main(String args[]){
Addition ad=new Addition (20,40); }
}

Output
Addition of two numbers: 60
 
Difference between Constructor and Method:

Java ConstructorJava Method
Constructor name must be same as the class name.Method name may or may not be same as class name.
It is invoked implicitlyMethod is invoked explicitly.
It does not contain any return type.It must contain return type.
The java compiler provides a default constructor if you do not contain any constructor.It is not provided by compiler.
It initializes the state of an object.It exposes behavior of an object.

Leave a Reply

Your email address will not be published. Required fields are marked *

Solve : *
23 + 1 =