问题
Hi I am just learning about constructor chaining in Java and had some questions...
First of all could someone please explain when I would ever need to use this? Off the top of my head I seriously cannot think of a situation.
In this example, within the constructor with no arguments I call another constructor. How do I access this new "James Bond" object for future use?
import java.util.*; class Employee { private String name; private double salary; public Employee() { this("James Bond", 34000); } public Employee(String n, double s) { name = n; salary = s; } public String getName() { return name; } public double getSalary() { return salary; } public static void main(String[] args) { Employee a = new Employee(); } }
回答1:
Actually I believe the most common use of chained Constructors is when the Constructor does more than just setting the member variables.
static int numOfExamples = 0;
public Example(String name, int num)
{
this.name = name;
this.num = num;
numOfExamples++;
System.out.println("Constructor called.");
Log.info("Constructor called");
}
public Example()
{
this("James Bond",3);
}
That way we don't have to write the code for logging and incrementing the static variable twice, instead just chaining the constructors.
回答2:
Chaining constructors like this is useful to avoid repeating code, and helps with maintainability:
public MyClass(int x, double y, String z) {
// set fields
}
public MyClass() { // i.e. a constructor that uses default values
this(42, 4.2, "hello world"); // x is 42, y is 4.2, and z is "hello world"
}
If we didn't use the chain, and wanted to change how the x
argument (for example) is processed when constructing an instance of MyClass
, we would have to change code in both constructors. With the chain, we only need to change one of them.
回答3:
1) As others have said, it's for code maintenance, basically the idea is that you only write one piece of code once, which means you only need to edit it once, there is no risk of overlooking something when editing your methods and the two accidentally becoming different.
Personally I tend to use this differently than in your example. Like so:
Employee() {
setupStuff();
}
Employee(String name) {
this();
this.setName(name);
}
This is a nice way of doing things, because potentially your setter can be way more complicated than just setting a member in the class. So basically what this does is puts calling the empty constructor and then a setter into a single method, making it much easier for anyone using the class.
2) The constructor being called doesnt't create a different object at all, it creates this object. Note that there is no new
keyword used. Basically you're just calling a different method inside your constructor, except that method happens to also be a constructor.
回答4:
How do I access this new "James Bond" object for future use?
Because you saved the values of name and salary as fields of your employee class, then inside the employee class you can use those fields, and outside your employee class you can use the getter/setter methos of your employee class
回答5:
Every time you want to allow constructing an object wit default values, and also want to allow creating the same object with non-default values. Let's imagine a
DateTime
class. You could want to initialize it with the current time by default, or with a specific time. Imagine aCar
class. You could imagine constructing it with Black as the default color, or with a specific color. This kind of situation is very common. Seejava.util.ArrayList
orjava.util.Locale
, for concrete examples.It's stored in the
name
field. So you access it, from the object itself, withthis.name
(this
being optional, just as in thegetName()
method).
来源:https://stackoverflow.com/questions/17640560/java-constructor-chaining