delsa delsa - 1 year ago 79
Java Question

how can I define a default constructor while I have other constructors?

I have a class in java. This class has a constructor like bellow

public Person(String first, String last) {
firstName = new SimpleStringProperty(first);
lastName = new SimpleStringProperty(last);
city = new SimpleStringProperty("Tehran");
street = new SimpleStringProperty("Vali Asr");
postalCode = new SimpleStringProperty("23456");
birthday = new SimpleStringProperty("12345");

now I want to declare a constructor like bellow

public Person() {
Person(null, null);

but it gives me error.
what can I do?

Answer Source

Calling Person(null, null) doesn't work because a constructor is not a method so it cannot be called like a method as you are trying to do. What you need to do is rather to call this(null, null) to invoke the other constructor as next:

public Person() {
    this(null, null); // this(...) like super(...) is only allowed if it is 
                      // the first instruction of your constructor's body

public Person(String first, String last) {

More details about the keyword this here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download