Learn Object-Oriented Java the Hard Way

Exercise 4: Fields in an Object

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.

TVActor.java
1 public class TVActor {
2     String name;
3     String role;
4 }

Then type up this one and save it in the same folder as the first file.

TVActorDriver.java
 1 public class TVActorDriver {
 2     public static void main( String[] args ) {
 3         TVActor a = new TVActor();
 4         a.name = "Thomas Middleditch";
 5         a.role = "Richard Hendricks";
 6 
 7         TVActor b = new TVActor();
 8         b.name = "Martin Starr";
 9         b.role = "Bertram Gilfoyle";
10 
11         TVActor c = new TVActor();
12         c.name = "Kumail Nanjiani";
13         c.role = "Dinesh Chugtai";
14 
15         System.out.println( a.name + " played " + a.role );
16         System.out.println( b.name + " played " + b.role );
17         System.out.println( c.name + " played " + c.role );
18     }
19 }

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.

What You Should See

[:::]

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