Practical-19
Write a java program which implements the Parameterized Constructors.
Answer
Introduction
Parameterized constructors are called when we pass arguments to it while creating an object. It helps us to initialize instance variables with specific values at the time of object creation. It is also used to pass different arguments when different objects are made, which allows for more flexibility in programming. Parameterized constructors are especially helpful when we want to give different values to the object when it’s made, as compared to using the same values for every object of the same type.
Code
class MyClass {
int x;
// Following is the constructor
MyClass(int i ) {
x = i;
}
public static void main(String args[]) {
MyClass myObj1 = new MyClass( 10 );
MyClass myObj2 = new MyClass( 20 );
System.out.println(myObj1.x);
System.out.println(myObj2.x);
}
}
Output
10
20
In the above code, we’ve created a parameterized constructor of the MyClass class which takes one integer argument and sets the instance variable x to the value which we passed as an argument while creating an object. We can create multiple objects of the same type and can assign different values to the x variable of each object by just providing different arguments to the parameterized constructor.