Reputation: 399
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?
Upvotes: 0
Views: 1475
Reputation: 5619
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.
Upvotes: 1
Reputation:
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.
Upvotes: 0
Reputation: 7821
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.
Upvotes: 0
Reputation: 19294
The empty constructor can use setters with default values.
public Cat()
{
setName(defaultName);
setYearOfBirth(defaultYearOfBirth);
setWeightInKilos(defaultWieghtInKilos);
}
Upvotes: 1