So far we have only looked at methods inside of objects. But most objects have variables inside them, too, called “fields” (or sometimes “instance variables”).
This program will illustrate accessing fields in an object.
Type up this code and save it in its own file, named as indicated.
Then type up this one and save it in the same folder as the first file.
Remember that you only need to compile the one file containing the main() method, though it is a good idea to test compiling each file as you finish it to make sure it’s correct before moving on.
So the class TVActor
contains two instance variables, and they are both
Strings. The first variable is called name and the second is called role.
They are called “instance” variables because each instance (copy) of the object gets its own copies of the variables.
That is, just after line 11 is over, there are three instances of the TVActor
class created. public class TVActor
makes a pattern or recipe or blueprint
of sorts, and then line 3 actually sews together the clothing or cooks the
recipe or builds the structure when it instantiates the object.
And so the instance named a has a copy of the name variable and a copy of the role variable. We can put values into a’s copies of these variables as shown on lines 4 and 5, though we’ll see later in the book that this is considered bad style.
Line 7 creates a second instance of the class, with its own copies of the instance variables.
And line 11 creates a third instance of the class, which also has its own
copies of the variables. So by line 14, there are at least nine objects floating
around in memory: three TVActor
objects and six String
objects (two per
TVActor).
“Learn Object-Oriented Java the Hard Way” is ©2015–2016 Graham Mitchell