Table of Contents
In this tutorial, you’ll learn about Constructors in Java, Syntax to declare constructor, Types of Constructor along with examples.
A constructors in java is a special method whose name is same as class name and is used to initialize an object. Every class has a constructor either implicitly or explicitly.
It is called when an instance of the class is created. At the time of calling the constructor, memory for the object is allocated in the memory.
Syntax to declare constructor
className (argument-list){
construction body
}
Example for constructor
class A
{
String var1;
String var2;
A( ) //Constructor
{
var1 ="";
var2 ="";
}
}
Types of Constructor
Java Supports two types of constructors:
- Default Constructor
- Parameterized constructor
A c = new A() //Default constructor invoked
A c = new A(parameter-list); //Parameterized constructor invoked
Default Constructor
A constructor is called “Default Constructor” when it doesn’t have any parameter.
Example for default constructor
class Add
{
Add()
{
int a=10;
int b=5;
int c;
c=a+b;
System.out.println("*****Default Constructor*****");
System.out.println("Total of 10 + 5 = "+c);
}
public static void main(String args[])
{
Add obj=new Add();
}
}
Parameterized constructor
A Constructor with arguments(or you can say parameters) is known as Parameterized constructor.
Example for Parameterized constructor
class Test{
int id;
String name;
Test(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Test t1 = new Student4(111,"Sachin");
Test t2 = new Student4(222,"Komal");
t1.display();
t2.display();
}
}