Learn how objects are initialized in Java
A constructor is a special block of code used to initialize objects when they are created. It is called automatically when an object of a class is instantiated using the new keyword[
voidabstract, static, or finalIf you don't write any constructor in your class, Java automatically provides a Default Constructor that sets variables to default values (e.g., 0, null, false)
class Student {
String name;
int rollNo;
// Default Constructor is added behind the scenes by Java Compiler!
// Student() { }
}
public class Main {
public static void main(String[] args) {
Student s = new Student(); // Calls default constructor
System.out.println(s.name); // Output: null
System.out.println(s.rollNo); // Output: 0
}
}
A constructor that accepts parameters is used to initialize object attributes with specific custom values upon creation
class Student {
String name;
int rollNo;
// Parameterized Constructor
Student(String n, int r) {
name = n;
rollNo = r;
}
}
public class Main {
public static void main(String[] args) {
// Passing arguments directly during instantiation
Student s1 = new Student("Anu", 101);
System.out.println(s1.name + " - " + s1.rollNo); // Output: Anu - 101
}
}
Having multiple constructors in the same class, each with a different parameter list (number or types of arguments)[cite: 2].
class Student {
String name;
int rollNo;
// Constructor 1: Default values
Student() {
name = "Unknown";
rollNo = 0;
}
// Constructor 2: Parameterized
Student(String name, int rollNo) {
name = name;
rollNo = rollNo;
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student(); // Calls Constructor 1
Student s2 = new Student("Rahul", 102); // Calls Constructor 2
}
}