Constructors:
A constructor in Java is a special member that is called when an object is created. It initializes the new object’s state. It is used to set default or user-defined values for the object's attributes
A constructor in Java is a special method that is automatically called when an object of a class is created. Its main purpose is to initialize the object's data.
- A constructor has the same name as the class.
- It does not have a return type, not even void.
- It can accept parameters to initialize object properties.
Rules:
- Constructor name must be the same as the class name.
- It does not have a return type (not even void).
- It is called automatically when you create an object using the new keyword.
- A class can have multiple constructors (constructor overloading).
Example
class Student {
String name;
int age;
Student() {
name = "Kamalesh";
age = 22;
}
void display() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
public static void main(String[] args) {
Student s1 = new Student();
s1.display();
}
}
Output:
Kamalesh
22
Constructor Overloading
Constructor overloading means having multiple constructors in the same class with different parameter lists.
Example
class Student {
String name;
int age;
// Constructor 1
Student() {
name = "Unknown";
age = 0;
}
// Constructor 2
Student(String n) {
name = n;
age = 0;
}
// Constructor 3
Student(String n, int a) {
name = n;
age = a;
}
void display() {
System.out.println(name + " " + age);
}
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student("Kamalesh");
Student s3 = new Student("Raju", 21);
s1.display();
s2.display();
s3.display();
}
}
Output
Unknown 0
Kamalesh 0
Raju 21
Here have a three constructors
Student()
Student(String n)
Student(String n, int a)
this Keyword
- Once you understand constructors, this becomes much easier.
- The this keyword refers to the current object.
- The most common use is when the instance variable and constructor parameter have the same name.
Without this
class Student {
String name;
int age;
Student(String name, int age) {
name = name;
age = age;
}
}
this with constructors
class Student {
String name;
int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
void display() {
System.out.println(this.name);
System.out.println(this.age);
}
public static void main(String[] args) {
Student s1 = new Student("Kamalesh", 22);
s1.display();
}
}
Output
Kamalesh
22
References:
https://www.geeksforgeeks.org/java/constructors-in-java/
https://www.w3schools.com/java/java_constructors.asp
https://www.programiz.com/java-programming/constructors
Top comments (0)