Parameterized Constructor in Java
A parameterized constructor is a constructor that accepts arguments, allowing you to initialize an object's fields with specific values at the time of its creation.
Syntax
class ClassName {
ClassName(parameterType parameterName) {
// initialization code
}
}
Example
class Student {
String name;
int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
}
Student s1 = new Student("Aman", 22);
Student s2 = new Student("Priya", 24);
Key Points
- Parameterized constructors let each object be initialized with different values right at creation
- Once a class defines a parameterized constructor, Java no longer provides a default no-arg constructor automatically
- A class can have multiple parameterized constructors through constructor overloading
Why Use Parameterized Constructors?
- Avoids the need to set every field manually with setters after creating the object
- Makes sure objects are created in a valid, fully-initialized state
- Improves readability, since the values passed during creation are visible at a glance
If you define only a parameterized constructor and try to create an object using
new ClassName() with no arguments, the code will not compile unless you also explicitly add a no-arg constructor.Master Java with Uncodemy
Hands-on training, live projects, and placement support in our Java Programming Course.