1.3.15 How to Define a Variable

Up until week 3 we have been assigning values to fields. Now that we are dealing with methods, however, we may need a method to have a value locally without being tied to a field reference. To do this we will define a variable and assign it a value.

So let's say we have a food that can melt. When we call that method currently it will reduce the Weight of the Food by 1. However, this would make Food that weighs 1lb disappear with one call.

Instead, what we'd like to do is reduce the the Food's Weight by a percent of its Weight rather than a set value.


The first thing we'd do, then, is define a variable with a type.

Note: Variable types will vary based on your need.

We get a green 'squiggly' because the variable is never assigned to. To assign a variable is the same as assigning to a field.

In this case, we are assigning the foodLoss variable to 20% of the Food's Weight, whatever that Food might be. So when we run the application and call the method...

...we can see that the foodLoss variable now 'holds' a value of 0.2, 20% of 1.


We can now use that variable to do things for us, like reduce the Weight of the Food object.

So now when we execute the method...

...we can see that the Weight of the Food object has now been reduced to 0.8.


Now, if the Food object continues to melt...

...the variable will change because the Weight of the Food object has changed.