Controlling Programs with Definitions
Student: Java can make more than just
Pict definitions, right?Prof: Absolutely, for example, we can make a definition of an
intStudent: OK, what is that good for?
Prof: Glad you asked! Let’s write a little program with some images again:
Prof: Now I want you to imagine that these are part of a logo or other design, OK?
Student: OK…
Prof: Say we wanted to make all the pieces three times as big. How would we do that?
Student: We’d change the 20 to 60, the 40s to 120s, and so on
Prof: Right, we’d edit 5 different numbers. But these numbers are related! The square sides are twice the circle radius, and so is the triangle width. We can use a definition to capture that:
Prof: Now we’ve defined that one
size. How would we make the images all three times as big now?Student: Oh! I get it. We could change
size to 60, or 100, or whatever we want and all the images would change when we re-run. 60 for the case you said, of making it three times as big.Prof: That’s just it. Defining a name in one place and using it in several makes it easier for us to update our program to do something new. There are other uses for definitions, too, but this is a good one (and it helps us make cool pictures).
Prof: Here’s one to try. Weight is mass times gravity. Below,
massKg is defined once and every planet’s weight is computed from it.Practice
Fill in a massKg so that weightOnEarth comes out to exactly 150. Then run it and see what the same mass weighs elsewhere.
;
int weightOnEarth = 10 * massKg;
int weightOnMoon = 2 * massKg;
int weightOnMars = 4 * massKg;
int weightOnJupiter = 25 * massKg;
int weightOnEarth = 10 * massKg;
int weightOnMoon = 2 * massKg;
int weightOnMars = 4 * massKg;
int weightOnJupiter = 25 * massKg;