On Day 17, we learn about constructors. A constructor is a special method in Java that runs automatically when an object is created. Its purpose is to initialize object fields. Constructors have the same name as the class and no return type (not even void).
1. Default Constructor
If no constructor is defined, Java provides a default one automatically. But we can also define our own.
class Student {
String name;
int age;
// default constructor
Student() {
name = "Unknown";
age = 0;
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student(); // calls default constructor
System.out.println(s1.name + " - " + s1.age);
}
}
Explanation: When new Student()
is called, the default constructor sets name
and age
with initial values.
2. Parameterized Constructor
A parameterized constructor lets us pass values when creating objects.
class Student {
String name;
int age;
// parameterized constructor
Student(String n, int a) {
name = n;
age = a;
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student("Alice", 20);
Student s2 = new Student("Bob", 22);
System.out.println(s1.name + " - " + s1.age);
System.out.println(s2.name + " - " + s2.age);
}
}
Explanation: When calling new Student("Alice", 20)
, the constructor assigns values to name
and age
.
3. Using Both Constructors
A class can have multiple constructors (constructor overloading).
class Student {
String name;
int age;
// default constructor
Student() {
name = "Unknown";
age = 0;
}
// parameterized constructor
Student(String n, int a) {
name = n;
age = a;
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student(); // default
Student s2 = new Student("Charlie", 21); // parameterized
System.out.println(s1.name + " - " + s1.age);
System.out.println(s2.name + " - " + s2.age);
}
}
Explanation: The class now supports creating objects with or without initial values.
Summary
Constructors are special methods used to initialize objects. A class can have a default constructor (no parameters) and parameterized constructors (with parameters). This flexibility makes object creation easier and cleaner.