Constructors in java
Constructor -: A Java constructor is special method that is called when an object is instantiated. In other words, when you use the new keyword. The purpose of a Java constructor is to initializes the newly created object before it is used. When object is created constructor will invoke automatically. It is special member function because its name is same as class name. It does not have any return type.
Example
Class Student
{
………
Student()//constructor
{
……..
}
Student s=new Student();
}
Rules for creating Java constructor
- Constructor name must be the same as its class name.
- A Constructor must have no explicit return type.
- A Java constructor cannot be abstract, static, final, and synchronized.
Types of Java constructors
Default constructor:-A constructor is called "Default Constructor" when it doesn't have any parameter.
Syntax of default constructor:
<class_name>(){}
Example of default constructor
class Student3
{
int id;
String name;
//method to display the value of id and name
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
//creating objects
Student3 s1=new Student3();
Student3 s2=new Student3();
//displaying values of the object
s1.display();
s2.display();
}
}
Output
0 null
0 null
Parameterized Constructor:-A constructor which has a specific number of parameters is called a parameterized constructor.
Example of parameterized constructor
class Student4
{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n)
{
id = i;
name = n;
Get Rashidautturkar’s stories in your inbox
Join Medium for free to get updates from this writer.
}
//method to display the values
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
//creating objects and passing values
Student4 s1 = new Student4(100,"Siya");
Student4 s2 = new Student4(200,"Riya");
//calling method to display the values of object
s1.display();
s2.display();
}
}
Output
100 Siya
200 Riya
Constructor Overloading in Java:-In Java, a constructor is just like a method but without return type. It can also be overloaded like Java methods.
Constructor overloading in Java is a technique of having more than one constructor with different parameter lists. They are arranged in a way that each constructor performs a different task. They are differentiated by the compiler by the number of parameters in the list and their types.
Example of Constructor Overloading
class Student5
{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n)
{
id = i;
name = n;
}
//creating three arg constructor
Student5(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[])
{
Student5 s1 = new Student5 (101,"Karan");
Student5 s2 = new Student5 (102,"Aryan",20);
s1.display();
s2.display();
}
}
Output
101 Karan 0
102 Aryan 20







