Default Constructor

suggest change

If you declare no constructors, the compiler generates a default constructor with no arguments.

This means the following two snippets are semantically equivalent:

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

    }
}

The generated constructor has the same visibility as the class. A package-private class gets a package-private default constructor.

If you declare any constructor, the compiler does not generate a default constructor. These two classes 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) {
    }
}

The generated constructor does not assign your fields. Each field keeps the default for its type unless a field initializer, or a constructor you write, sets it.

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