Question

If I was to make a simple class in Java with only an array of integers for an instance variable, then what would make sense for a default constructor? I don't want to leave it empty.

Was it helpful?

Solution

You can do this:

public class IntArrayDemo {
    private static final int DEFAULT_SIZE = 10;
    private int [] values;

    public IntArrayDemo() {
        this(DEFAULT_SIZE);
    }

    public IntArrayDemo(int size) { 
        if (size < 0) throw new IllegalArgumentException("size cannot be negative");
        this.values = new int[size];
    }
}

OTHER TIPS

There is nothing wrong in empty constructor. If you really want to fill it somehow, you can inititalize your list:

//...
private SIZE = 10;
private int [] list;

public MyClass() {
  list = new int [SIZE];
}

If you want to set the contained array while instantiating the class, you should use the array as an argument to the constructor. Otherwise an empty constructor is just fine (you don't need to declare it explicitly, every class without an explicit constructor has an empty one by default).

public class ArrayWrapper {
    private final int[] innerArray;

    public ArrayWrapper(int[] values) {
        this.innerArray = values;
    }
}

You do not need a default constructor. You can use static initialization. http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top