0

So while reading a book, I came upon this code.

public class NutritionFacts {
private final int servingSize; // (mL) required
private final int servings; // (per container) required
private final int calories; // (per serving) optional
private final int fat; // (g/serving) optional
private final int sodium; // (mg/serving) optional
private final int carbohydrate; // (g/serving) optional
public NutritionFacts(int servingSize, int servings) {
this(servingSize, servings, 0);
}

public NutritionFacts(int servingSize, int servings,
int calories) {
this(servingSize, servings, calories, 0);
}

public NutritionFacts(int servingSize, int servings,
int calories, int fat) {
this(servingSize, servings, calories, fat, 0);
}

public NutritionFacts(int servingSize, int servings,
int calories, int fat, int sodium) {
this(servingSize, servings, calories, fat, sodium, 0);
public NutritionFacts(int servingSize, int servings,
int calories, int fat, int sodium, int carbohydrate) {
this.servingSize = servingSize;
this.servings = servings;
this.calories = calories;
this.fat = fat;
this.sodium = sodium;
this.carbohydrate = carbohydrate;
}
}

So here, the final keyword is used before the nutrition names. But they are also initialized in the later part of the code. Is that possible? Because once a variable is marked final, it cannot be initialized later.

  • it isn't "used before" the nutriton names. Those nutriton names are constructors, they are the ones that initialize your object. If at the end of the execution of your constructor your final variable doesn't have a value, that's when you might have a problem. – Stultuske Sep 28 '20 at 07:33

1 Answers1

0

The final keyword means that the value of an attribute can only be set once. And this is the case here because you only set the value in your constructor. So this is valid code.

Milgo
  • 2,617
  • 4
  • 22
  • 37