Search code examples
javaparametersconstructordefault-constructor

Are Java constructors only called when they are parameterized?


Apparently Java thinks my constructor code is not important, so it completely ignores it and then yells at me with a NullPointerException when I try to access an ArrayList that I thought was initialized. Only when I add an arbitrary parameter to my constructor does Java think it's worth looking at.

import java.util.ArrayList;

public class DataManager {
    ArrayList<Variable> vars;

    public DataManager() {
        vars = new ArrayList<Variable>();
    }

    public void createVar(String type, String name, String strValue, int numValue) {
        vars.add(new Variable(type, name, strValue, numValue));
    }
}

And the code that calls this:

DataManager data = new DataManager();
data.createVar(...);

Variable class:

class Variable {
    String type;
    String name;
    String strValue;
    int numValue;

    public Variable(String type, String name, String strValue, int numValue) {
            this.type = type; this.name = name;
            this.strValue = strValue;
            this.numValue = numValue;
    }
}

Running this results in

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at Parser.start(Parser.java:25) at SudoCode.go(SudoCode.java:10) at SudoCode.main(SudoCode.java:6)

So... what's the deal? Why are constructors ignored when they aren't parameterized? It's just not very intuitive. Was this some sort of design choice that I can't see the obvious implications of? If so, enlighten me. And should I just add an arbitrary parameter so the constructor is executed, or should I create and explicitly call a method designed solely to initialize my ArrayList?

Thanks!


Solution

  • Your assumption is false. You cannot instantiate an object without having its constructor execute.

    If you define a class without a constructor, Java will create an implicit ("default") constructor without parameters.