I have this class constructor:
public Category(int max){
...
}
The thing is, I want to make an array of this class, how do I initialize it?
private Category categories = new Category(max)[4];
Does not work.
UPDATE
Do I need to do something like this?
private Category[] categories = new Category[4];
And then initialize each object?
One way to initialize the array of objects is by using the constructors. When you create actual objects, you can assign initial values to each of the objects by passing values to the constructor. You can also have a separate member method in a class that will assign data to the objects.
You can initialize the array variable which is declared inside the class just like any other value, either using constructor or, using the setter method.
Array#newInstance to initialize our generic array, which requires two parameters. The first parameter specifies the type of object inside the new array. The second parameter specifies how much space to create for the array.
A constructor reference is similar to method reference except that the name of a method is new. We can also create a constructor reference with an array type. For instance, if we need to create an integer array by using the constructor reference: int[]:: new, where the parameter is a length of an array.
When you are making an array , you are creating an array of Category. That s an instance of array.
When you are populating the array with Category objects, at that point you use the Category with Const.
Category [] categories = new Category[4];
categories[0] = new Category(10);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With