Default Constructor

suggest change

The “default” for constructors is that they do not have any arguments. In case you do not specify any constructor, the compiler will generate a default constructor for you.

This means the following two snippets are semantically equivalent:

public class TestClass {
    private String test;
}
public class TestClass {
    private String test;
    public TestClass() {

    }
}

The visibility of the default constructor is the same as the visibility of the class. Thus a class defined package-privately has a package-private default constructor

However, if you have non-default constructor, the compiler will not generate a default constructor for you. So these are not equivalent:

public class TestClass {
    private String test;
    public TestClass(String arg) {
    }
}
public class TestClass {
    private String test;
    public TestClass() {
    }
    public TestClass(String arg) {
    }
}

Beware that the generated constructor performs no non-standard initialization. This means all fields of your class will have their default value, unless they have an initializer.

public class TestClass {

    private String testData;

    public TestClass() {
        testData = "Test"
    }
}

Constructors are called like this:

TestClass testClass = new TestClass();

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents