Constructors can also take parameters, which is used to initialize attributes.
The following example adds an int y
parameter to the constructor. Inside the constructor we set x to y (x=y). When we call the constructor, we pass a parameter to the constructor (5), which will set the value of x to 5:
Example
public class Main {
int x;
public Main(int y) {
x = y;
}
public static void main(String[] args) {
Main myObj = new Main(5);
System.out.println(myObj.x);
}
}
// Outputs 5
You can have as many parameters as you want:
Example
public class Main {
int modelYear;
String modelName;
public Main(int year, String name) {
modelYear = year;
modelName = name;
}
public static void main(String[] args) {
Main myCar = new Main(1969, "Mustang");
System.out.println(myCar.modelYear + " " + myCar.modelName);
}
}
// Outputs 1969 Mustang
Practice Excercise Practice now