A constructor in Java is a special method that is automatically called when an object is created. It is mainly used to initialize objects with default or custom values.
Java provides different types of constructors based on how objects are initialized. The most common ones are default constructors and parameterized constructors.
// Class demonstrating a default constructor
class Student {
int id;
String name;
Student() {
// Default constructor initializes values
id = 1;
name = "Unknown";
}
void display() {
System.out.println(id + " " + name);
}
}
public class Main {
public static void main(String[] args) {
// Object creation triggers constructor call
Student s1 = new Student();
s1.display();
}
}
// Class demonstrating a parameterized constructor
class Employee {
int empId;
String empName;
Employee(int id, String name) {
// Parameterized constructor assigns values
empId = id;
empName = name;
}
void show() {
System.out.println(empId + " " + empName);
}
}
public class Main {
public static void main(String[] args) {
// Passing values during object creation
Employee e1 = new Employee(101, "Amit");
e1.show();
}
}
Fill in the fields to simulate a Parameterized Constructor, or just click "Default" to see a Default Constructor in action.
1 Unknown
101 Amit
When an object is created, the constructor runs automatically and initializes the data members.