Array initialization with default constructor

前端 未结 6 1375
渐次进展
渐次进展 2020-11-30 09:15
public class Sample
{
     static int count = 0;
     public int abc;
     public Sample()
     {
        abc = ++Sample.count;
     }
}

I want to

6条回答
  •  伪装坚强ぢ
    2020-11-30 09:30

    The problem is that by declaring that array, you never allocated space for each object. You merely allocated space for 100 objects of type Sample. You'll have to call the constructor on each yourself.

    To elaborate:

    Food[] foods = Food[100];
    for (int k = 0; k < foods.length; k++) {
       foods[k] = new Food();
    }
    

    An interesting work around might be a factory function. Consider attaching this to your Sample class.

    public static Sample[] getInstances(int aNumber) {
        Sample[] sample = Sample[aNumber];
        for (int k = 0; k < sample.length; k++) {
           sample[k] = new Sample();
        }
    
        return sample;
    }
    

    Hides the blemish, a bit - providing this is a useful function to you.

提交回复
热议问题