Why use the parameterized constructor in Java?
Java Programming Language > Class, Object and Methods in java > Constructor
830
Answer:
The parameterized constructor is used to provide different values to the distinct objects. However, you can provide the same values also.
Example of parameterized constructor
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
This Particular section is dedicated to Question & Answer only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.
Join Our telegram group to ask Questions
Click below button to join our groups.