CHAPTER 6: Android Screen Design: Writing to the Display Using Activity and View 205
Doing this will allow every method in your class to now be able to “see” and reference your Galaxy
object. The other code that sets your Galaxy object’s attributes using dot notation to call your Galaxy
class methods can stay inside of the createDefaultGalaxy( ) method.
As you can see in Figure 6-35, once you place this Galaxy constructor line of code at the top of your
class, the error highlighting disappears, because the milkyWay Galaxy object is now visible to every
method in the class.
Figure 6-35. Moving the Galaxy object declaration and instantiation outside of the createDefaultGalaxy( ) method
If you remember earlier, I said I would show you two different ways to instantiate an object in
Java, and now you have done this using one line of code (Galaxy object) in one location, or two
lines of code (TextView objects) in two different locations (inside of, as well as outside of, a method).
To clarify the difference, you could also split the Galaxy object instantiation using just the
Galaxy milkyWay; part, called the object “declaration,” at the top of the class and insert the
milkyWay = Galaxy("Milky Way", 511, 97); part in createDefaultGalaxy( ).
You can try this second (split) coding as an “exercise” for this chapter, if you like; it is a cool way
to make your object declaration(s) visible to your entire class, while actually instantiating the object
inside of whichever method you wish to do so. On the other hand, the long-form (object declaration
and instantiation all using one single line of code) uses less code, which is said to be more
“compact” code, in programming terminology.