Java Language Constructors Default Constructor

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

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();


Got any Java Language Question?