How would you use a constructor to initialize an array

date:2024-06-05 12:33:13 author:admin browse: View comments Add Collection

How would you use a constructor to initialize an array

How would you use a constructor to initialize an array?

A constructor can be used to initialize an array in a class. For instance, consider a class ‘ArrayClass’ with an integer array as its member. The constructor of this class could take an array as parameter and copy the elements into the member array.

Here’s a simple example in Java:

public class ArrayClass {
    private int[] arr;
    public ArrayClass(int[] inputArr) {
        this.arr = new int[inputArr.length];
        for (int i = 0; i < inputArr.length; i++) {
            this.arr[i] = inputArr[i];
        }
    }
}
In this code, ArrayClass has a constructor that takes an integer array as argument. It initializes the member array arr with the same length as inputArr, then copies each element from inputArr to arr.

支付宝转账赞助

支付宝扫一扫赞助

微信转账赞助

微信扫一扫赞助