Parameterized Constructor in Java
A parameterized constructor in Java is a constructor that accepts arguments (parameters)
to initialize an object with specific values when it is created. Unlike the default
constructor (which takes no arguments), a parameterized constructor allows you to set
initial values for object attributes.
Example:
class Student {
String name;
int age;
// Parameterized constructor
Student(String n, int a) {
name = n;
age = a;
}
void display() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
// Creating object using parameterized constructor
Student s1 = new Student("Alice", 20);
Student s2 = new Student("Bob", 22);
s1.display();
s2.display();
}
}
Output:
Name: Alice
Age: 20
Name: Bob
Age: 22
Key Points:
- Allows object initialization with user-defined values.
- Can be overloaded with different parameter lists.
- If you define any constructor, Java does not provide a default constructor unless you explicitly
define it.