You'd have to ask your prof, that is not exactly front and center in the 'dos and donts of java' list. However, for your specific snippet, perhaps your prof is getting at a slightly different point:
There is absolutely no purpose whatsoever to what you are doing here, or, if there is, your code is broken.
There are only two options:
This is the one and only place in your entire codebase that refers to the calories field, or
There are other places where you use that field.
option 1 - this is the only place you use it.
Then it's useless. You calculate the calories, every time someone calls getCalories(). Java is not voodoo magic; if a method is called, each line in it is executed in order. Adding a field like this just.. also means java will store that result in that field. It doesn't mean that java will skip the calculation next time!
So, your getCalories() call will do the calculation, store the result AND return the result. The stored result is not used anywhere, and is a total waste of space. Fix: Just.. don't store it. Delete the field. Make that method a oneliner (replace this.calories = with return .
option 2 - you use it elsewhere
let's say you have another method in this class:
public boolean exceedsRecommendedDaily() {
return this.calories > 2000;
}
then this code is BROKEN - if I invoke this method, then the calories field is still 0 and will remain 0 until someone calls getCalories(). I guess we can fix it by documenting this behaviour like so:
/**
* Calculates if this food item on its own exceeds recommended daily intake.
* NB: If you haven't called `getCalories()` earlier on this object,
* this method will straight up lie to you!
*/
but I think we can all agree that means the method is idiotic.
No, why not just do it like this:
public boolean exceedsRecommendedDaily() {
return getCalories() > 2000;
}
tada. No need for silly caveats any more.
So.. is it a best practice?
No, it is not. IF the calculation takes long enough, and the result of the calculation is needed often enough, and the object is immutable (has no set methods / none of the fields can ever change after construction) or its worthwhile for every field update to also clear out a cached value, then it is a good idea to cache the value.
For example, java's very own java.lang.String caches the hashcode, because calculating that is quite an expensive operation (it at least requires inspecting every character. So in a string of 1 million characters, that takes a while!), it can be called a ton, and strings are immutable.