In my assignment, I'm given a Food
class like this:
class Food { private String name; // name of food private int calPerServing; // calories per serving // must be >= 0 // min storage temperature // must be >= 0. // max storage temperature // must be <= 100. private float minTemp; private float maxTemp; int getCalories() { return calPerServing; } }
And I'm having trouble with this part of the assignment:
Write a constructor method for the
Food
class, to set the defaultname
to"Pie"
, the defaultcalPerServing
to500
, the defaultminTemp
to25
, and the defaultmaxTemp
to75
.
How do I set default values for name
, calPerServing
, etc.?
(I'm surprised to get to page three of search results without finding a simple version of this question to point to.)
You have two choices for setting the default value of an instance variable (sometimes called an "instance field"):
Using an initializer on the declaration.
Using an assignment in a constructor.
Say I have a class Example
and an instance variable answer
whose default should be 42. I can either:
// Example of #1 (initializer)
class Example {
private int answer = 42;
// ...
}
or
// Example of #2 (assignment within constructor)
class Example {
private int answer;
Example() {
this.answer = 42;
}
}
Initializers (#1) are processed during construction just before any other logic in your constructor (but after calling the superclass constructor).
Which you use depends on the class and, to an extent, personal style. If the class is going to have multiple constructors but I want answer
to default to 42 regardless of which constructor is used, using initialization makes sense because then I just put it in one place instead of putting it in every constructor. If the default for answer
will vary depending on which constructor is used, or depending on a parameter the constructor(s) receives/receive, setting it in the constructor makes sense.
In your specific case, the assignment tells you to use a constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With