Yes, a constructor in Java can take one or more arrays as parameters when an object is instantiated. This allows the constructor to receive and process arrays during object creation.
Example: Passing a Single Array to a Constructor
class Student {
private int[] scores;
// Constructor accepting an array
public Student(int[] scores) {
this.scores = scores;
}
public void displayScores() {
for (int score : scores) {
System.out.print(score + " ");
}
System.out.println();
}
}
public class Test {
public static void main(String[] args) {
int[] marks = {90, 85, 88, 92};
Student student = new Student(marks);
student.displayScores(); // Output: 90 85 88 92
}
}
Here, the constructor "accepts an integer array" and assigns it to the instance variable.
Example: Passing Multiple Arrays to a Constructor
class Employee {
private String[] names;
private double[] salaries;
// Constructor accepting multiple arrays
public Employee(String[] names, double[] salaries) {
this.names = names;
this.salaries = salaries;
}
public void displayEmployees() {
for (int i = 0; i < names.length; i++) {
System.out.println(names[i] + " earns $" + salaries[i]);
}
}
}
public class Test {
public static void main(String[] args) {
String[] employees = {"Alice", "Bob", "Charlie"};
double[] salaries = {50000.0, 60000.0, 55000.0};
Employee emp = new Employee(employees, salaries);
emp.displayEmployees();
}
}
Here, the constructor accepts two arrays (`String[]` and `double[]`), and the object processes both.
Key Points
- Any type of array can be passed (primitive or reference types).
- Multiple arrays can be passed as parameters.
- Arrays are passed by reference, meaning modifications inside the constructor affect the original array.