In Java, a constructor is a special method that is used to initialize an object when it is created. Unlike regular methods, constructors are called automatically when you use the new keyword.
A constructor has some unique characteristics:
- Its name is the same as the class name
- It is called automatically when an object is created
- It is mainly used to initialize object variables
Simple Program using constructor:
Scenario 1:When a student is registered, roll number and name are mandatory.So they must be passed during object creation.
package Constructor;
public class Student {
int roll_no;
String name;
Student(int roll_no,String name)
{
this.roll_no=roll_no;
this.name = name;
}
Student(int roll_no){
this.roll_no=roll_no;
}
Student(String name){
this.name=name;
}
public static void main(String[] args)
{
Student user1 = new Student(1,"Kavitha");
Student user2 = new Student(2,"Arun");
System.out.println("Roll No: " + user1.roll_no);
}
}
Why constructor here?
1.Student must have roll number
2.Prevents invalid objects like Student() with no data
Scenario 2:
When you open a bank account, details like account number, name, and balance must be set at the time of creation.
class Bank
{
int accountNo;
String name;
int balance;
Bank(int accountNo, String name , int balance)
{
this.accountNo = accountNo;
this.name = name;
this.balance = balance;
}
public static void main(String[] args)
{
Bank accholder = new Bank(101,"kumar",1000);
System.out.println(accholder.accountNo);//101
Bank accholder1 = new Bank(102,"hari",1000);
System.out.println(accholder1.accountNo); //102
}
}
Why constructor here?
1.Account cannot exist without details
2.Values are initialized immediately
3.No chance of creating an incomplete object
Scenario 3:
Imagine a training institute called Payilagam that manages student or user accounts.
class Payilagam
{
String name;
String email;
String password;
Payilagam(String name, String email, String password)
{
this.name = name;
this.email = email;
this.password = password;
}
Payilagam( String email, String password)
{
this.email = email;
this.password = password;
}
public static void main(String[] args)
{
Payilagam user1 = new Payilagam("kumar","abc.com","kumar@123");
Payilagam user2 = new Payilagam("abc.com","kumar@123");
}
}
Why constructor here?
- Initialize user details when an object is created
- Ensure user data is stored correctly at the start
- Support different user actions (Registration vs Login)
this keyword
- The this keyword in Java is used to refer to the current object of a class.
- It helps avoid confusion between instance variables and constructor/method parameters that have the same name.
Constructor overloading:
Constructor overloading allows creating objects in different ways by using multiple constructors with different parameters.
How to Achieve a Constructor in Java?
https://dev.to/kavitha_krish/how-to-achieve-a-constructor-in-java-1gi3
Top comments (0)