Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set default values for instance variables?

Tags:

java

object

set

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 default name to "Pie", the default calPerServing to 500, the default minTemp to 25, and the default maxTemp to 75.

How do I set default values for name, calPerServing, etc.?

like image 633
Begüm Sakin Avatar asked Apr 20 '17 04:04

Begüm Sakin


1 Answers

(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"):

  1. Using an initializer on the declaration.

  2. 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.

like image 80
T.J. Crowder Avatar answered Oct 14 '22 09:10

T.J. Crowder