I am working on an assignment that asks me to create "a default constructor and a second constructor that expects all three values to be passed as parameters. Call the “set” methods from both constructors" I have done the second constructor as follows;
public Cat(String newName, int newYearOfBirth, int newWieghtInKilos )
{
setName(newName);
setYearOfBirth(newYearOfBirth);
setWeightInKilos(newWieghtInKilos);
}
How do I create a default constructor that calls a set method?
The empty constructor can use setters with default values.
public Cat()
{
setName(defaultName);
setYearOfBirth(defaultYearOfBirth);
setWeightInKilos(defaultWieghtInKilos);
}
You may tell the assignee that calling the set methods from both constructors is a wrong practice. Your default constructor may happily use the parameter constructor with default values.
public Cat(){
this("",0,0);
}
This will help in code reusing.
You can simply set the default values in the default constructor.
public Cat() {
setName("MyName");
setYearOfBirth(1987);
setWeightInKilos(55);
}
Alternatively, you can also set empty values.
You can call the setters from the default constructor in the same manner as you're doing in the overloaded constructor.
The only difference here is that in the default constructor you're not given any values to pass to the setters.
However if you want those fields to be initialized with default values, you can invoke the setters with those default values.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.