I have two questions about the following code.
1. How to constructor the third constructor without using setter?
2. what does this() do in the last constructor.
public class Person {
private String name;
private String address;
Person(){}
Person(String name){
this.name = name;
}
Person(String address){
//Person(java.lang.String) is already defined.
}
Person(String name,String address){
this();
this.name = name;
this.address = address;
}
}
My solution for question is
Person(Object address){
this.address = (String)address;
}
However, i am not sure about this.
and i think this(); in the last constructor calls constructor Person(){}, but if it does, is it mean that two Person objects are created when i call
Person p = new Person("myName","myAddress");
Thanks!!!
The problem with
Person(String name)andPerson(String address)is that you can’t have two constructors with the same parameters. The compiler will not know which one to call when you want to call something like this:new Person("Joe Blow");You could do something like this instead:
The “
this()” in your last constructor is just telling that constructor to call the default constructor as part of the process of constructing the object. It does not create two objects, it just runs the code in the def. constructor, which in your case, does nothing.