Constructors in Java Explained
Java Constructors
Special methods initializing objects automatically.
Multiple Constructors
public class Student {
String name;
int age;
// Default constructor
public Student() {
this.name = "Unknown";
this.age = 0;
}
// Parameterized constructor
public Student(String name, int age) {
this.name = name;
this.age = age;
}
}Key Points
- No return type, same name as class.
- Default constructor auto-generated if none exists.
- Constructor overloading provides flexibility.
this()calls another constructor.