Explanatory Question
Why use the parameterized constructor in Java?
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.
The parameterized constructor is used to provide different values to the distinct objects. However, you can provide the same values also.
In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor.
//Java Program to demonstrate the use of parameterized constructor
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}
111 Karan 222 Aryan
First read the answer fully, then try to explain it in your own words. After that, open a few related questions and compare the concepts. This method helps you remember the topic for a longer time and improves exam preparation.