Constructor in java
Source: Dev.to
What is Constructors?
A constructor is a special method in Java that is automatically executed when an object of a class is created. It is mainly used to initialize data members of a class.
Unlike normal methods, a constructor:
- Has the same name as the class.
- Does not have a return type.
- Is called automatically using the
newkeyword.
Why do we need Constructors?
Constructors are used because they:
- Initialize object data at the time of creation.
- Assign default or user‑defined values.
- Ensure the object starts in a valid state.
Types of Constructors in Java
Default Constructor
A constructor with no parameters is called a default constructor.
class Student {
Student() {
System.out.println("Default constructor called");
}
}
class Main {
public static void main(String[] args) {
Student s = new Student();
}
}
Parameterized Constructor
A constructor that accepts parameters is called a parameterized constructor.
class Student {
String name;
int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
void display() {
System.out.println(name + " " + age);
}
}
Constructor Overloading
When a class has multiple constructors with different parameters, it is called constructor overloading.
class Student {
Student() {
System.out.println("Default constructor");
}
Student(String name) {
System.out.println("Student name: " + name);
}
}
Rules of Constructors in Java
- Constructor name must be the same as the class name.
- Constructors do not have a return type.
- Constructors can be overloaded.
- Constructors cannot be inherited.
- If no constructor is defined, Java provides a default constructor.
this Keyword in Constructors
The this keyword refers to the current object of the class. It is commonly used when constructor parameters have the same name as instance variables.
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 acc1 = new Bank(101, "Kumar", 1000);
Bank acc2 = new Bank(102, "Hari", 1500);
System.out.println(acc1.accountNo);
System.out.println(acc2.accountNo);
}
}