Breakdown of Your Code
Let’s analyze the structure of the parameterized constructor you provided:
class Student {
String name;
int age;
// Parameterized Constructor
Student(String n, int a) {
name = n; // "n" is assigned to the object's name
age = a; // "a" is assigned to the object's age
}
}
String n, int a: These are the parameters. They act as “placeholders” for the data you will send.Assignment: The code inside the
{}takes the values from the parameters and stores them in the class variables (nameandage).
2. How to Use It (The Main Method)
When using a parameterized constructor, you provide the values inside the parentheses of the new statement.
public class Main {
public static void main(String[] args) {
// One-line creation and initialization
Student s1 = new Student("Ali", 15);
Student s2 = new Student("Sara", 18);
System.out.println(s1.name + " is " + s1.age); // Output: Ali is 15
System.out.println(s2.name + " is " + s2.age); // Output: Sara is 18
}
}
3. Advantages for Students
Using this type of constructor is standard practice in Java for several reasons:
Efficiency: You don’t need to write
s1.name = "Ali";ands1.age = 15;on separate lines. It saves time and space.Mandatory Data: You can force a rule that “No student can be created without a name.” If someone tries to write
new Student();, the code will not compile, preventing “empty” data errors.Multiple Objects: It makes it very easy to initialize hundreds of objects in a loop or an array.
4. Important Rule: The “Disappearing” Default Constructor
This is a very common Multiple Choice Question (MCQ) in university exams:
Rule: Once you define any parameterized constructor in your class, Java stops providing the automatic Default Constructor.
If you want to be able to create a student both ways—with data and without data—you must manually write both constructors in your class. This is called Constructor Overloading.
5. Summary Table
| Feature | Default Constructor | Parameterized Constructor |
| Arguments | No arguments (Empty). | Has one or more arguments. |
| Values | Assigns default values (0, null). | Assigns values provided by the user. |
| Creation | Provided by Java automatically. | Must be written by the programmer. |
| Purpose | To create a blank object. | To create an object with specific data. |
Practice Scenario:
Imagine you are building a Library System. You have a class Book.
Attributes:
title,author.Task: Create a parameterized constructor so you can create a book like this:
Book b1 = new Book(“Java Basics”, “James Gosling”)