Chapter 4. Methods Use Instance Variables: How Objects Behave

image with no caption

State affects behavior, behavior affects state. We know that objects have state and behavior, represented by instance variables and methods. But until now, we haven’t looked at how state and behavior are related. We already know that each instance of a class (each object of a particular type) can have its own unique values for its instance variables. Dog A can have a name “Fido” and a weight of 70 pounds. Dog B is “Killer” and weighs 9 pounds. And if the Dog class has a method makeNoise(), well, don’t you think a 70-pound dog barks a bit deeper than the little 9-pounder? (Assuming that annoying yippy sound can be considered a bark.) Fortunately, that’s the whole point of an object—it has behavior that acts on its state. In other words, methods use instance variable values. Like, “if dog is less than 14 pounds, make yippy sound, else...” or “increase weight by 5”. Let’s go change some state.

Remember: a class describes what an object knows and what an object does

A class is the blueprint for an object. When you write a class, you’re describing how the JVM should make an object of that type. You already know that every object of that type can have different instance variable values. But what about the methods?

image with no caption

Can every object of that type have different method behavior?

Well... sort of.*

Every instance of a particular class has the same methods, but the methods can behave differently based on the value of the instance variables.

The Song class has two instance variables, title and artist. The play() method plays a song, but the instance you call play() on will play the song represented by the value of the title instance variable for that instance. So, if you call the play() method on one instance you’ll hear the song “Politik”, while another instance plays “Darkstar”. The method code, however, is the same.

void play() {
    soundPlayer.playSound(title);
}
image with no caption
Song t2 = new Song();
t2.setArtist("Travis");
t2.setTitle("Sing");
Song s3 = new Song();
s3.setArtist("Sex Pistols");
s3.setTitle("My Way");

The size affects the bark

A small Dog’s bark is different from a big Dog’s bark.

The Dog class has an instance variable size, that the bark() method uses to decide what kind of bark sound to make.

image with no caption
image with no caption
image with no caption

You can send things to a method

Just as you expect from any programming language, you can pass values into your methods. You might, for example, want to tell a Dog object how many times to bark by calling:

d.bark(3);

Depending on your programming background and personal preferences, you might use the term arguments or perhaps parameters for the values passed into a method. Although there are formal computer science distinctions that people who wear lab coats and who will almost certainly not read this book, make, we have bigger fish to fry in this book. So you can call them whatever you like (arguments, donuts, hairballs, etc.) but we’re doing it like this:

A method uses parameters. A caller passes arguments.

Arguments are the things you pass into the methods. An argument (a value like 2, “Foo”, or a reference to a Dog) lands face-down into a... wait for it... parameter. And a parameter is nothing more than a local variable. A variable with a type and a name, that can be used inside the body of the method.

But here’s the important part: If a method takes a parameter, you must pass it something. And that something must be a value of the appropriate type.

image with no caption

You can get things back from a method

Methods can return values. Every method is declared with a return type, but until now we’ve made all of our methods with a void return type, which means they don’t give anything back.

void go() {
}

But we can declare a method to give a specific type of value back to the caller, such as:

int giveSecret() {
  return 42;
}

If you declare a method to return a value, you must return a value of the declared type! (Or a value that is compatible with the declared type. We’ll get into that more when we talk about polymorphism in Chapter 7 and Chapter 8.)

image with no caption

The compiler won’t let you return the wrong type of thing.

Whatever you say you’ll give back, you better give back!

image with no caption

Note

The bits representing 42 are returned from the giveSecret() method, and land in the variable named theSecret.

You can send more than one thing to a method

Methods can have multiple parameters. Separate them with commas when you declare them, and separate the arguments with commas when you pass them. Most importantly, if a method has parameters, you must pass arguments of the right type and order.

Calling a two-parameter method, and sending it two arguments

image with no caption

You can pass variables into a method, as long as the variable type matches the parameter type

image with no caption

Java is pass-by-value. That means pass-by-copy

image with no caption
  1. Declare an int variable and assign it the value ‘7’. The bit pattern for 7 goes into the variable named x.

    image with no caption
  2. Declare a method with an int parameter named z.

    image with no caption
  3. Call the go() method, passing the variable x as the argument. The bits in x are copied, and the copy lands in z.

    image with no caption
  4. Change the value of z inside the method. The value of x doesn’t change! The argument passed to the z parameter was only a copy of x.

    The method can’t change the bits that were in the calling variable x.

    image with no caption

Note

image with no caption

Reminder: Java cares about type!

You can’t return a Giraffe when the return type is declared as a Rabbit. Same thing with parameters. You can’t pass a Giraffe into a method that takes a Rabbit.

Cool things you can do with parameters and return types

Now that we’ve seen how parameters and return types work, it’s time to put them to good use: Getters and Setters. If you’re into being all formal about it, you might prefer to call them Accessors and Mutators. But that’s a waste of perfectly good syllables. Besides, Getters and Setters fits the Java naming convention, so that’s what we’ll call them.

Getters and Setters let you, well, get and set things. Instance variable values, usually. A Getter’s sole purpose in life is to send back, as a return value, the value of whatever it is that particular Getter is supposed to be Getting. And by now, it’s probably no surprise that a Setter lives and breathes for the chance to take an argument value and use it to set the value of an instance variable.

image with no caption
class ElectricGuitar {

   String brand;
   int numOfPickups;
   boolean rockStarUsesIt;

   String getBrand() {
      return brand;
   }

   void setBrand(String aBrand) {
      brand = aBrand;
   }

   int getNumOfPickups() {
      return numOfPickups;
   }

   void setNumOfPickups(int num) {
      numOfPickups = num;
   }

   boolean getRockStarUsesIt() {
      return rockStarUsesIt;
   }

   void setRockStarUsesIt(boolean yesOrNo) {
      rockStarUsesIt = yesOrNo;
   }
}
image with no caption

Encapsulation

Do it or risk humiliation and ridicule

Until this most important moment, we’ve been committing one of the worst OO faux pas (and we’re not talking minor violation like showing up without the ‘B’ in BYOB). No, we’re talking Faux Pas with a capital ‘F’. And ‘P’.

Our shameful transgression?

Exposing our data!

Here we are, just humming along without a care in the world leaving our data out there for anyone to see and even touch.

image with no caption

You may have already experienced that vaguely unsettling feeling that comes with leaving your instance variables exposed.

Exposed means reachable with the dot operator, as in:

theCat.height = 27;

Think about this idea of using our remote control to make a direct change to the Cat object’s size instance variable. In the hands of the wrong person, a reference variable (remote control) is quite a dangerous weapon. Because what’s to prevent:

image with no caption

This would be a Bad Thing. We need to build setter methods for all the instance variables, and find a way to force other code to call the setters rather than access the data directly.

Note

By forcing everybody to call a setter method, we can protect the cat from unacceptable size changes.

image with no caption

Hide the data

Yes it is that simple to go from an implementation that’s just begging for bad data to one that protects your data and protects your right to modify your implementation later.

OK, so how exactly do you hide the data? With the public and private access modifiers. You’re familiar with public–we use it with every main method.

Here’s an encapsulation starter rule of thumb (all standard disclaimers about rules of thumb are in effect): mark your instance variables private and provide public getters and setters for access control. When you have more design and coding savvy in Java, you will probably do things a little differently, but for now, this approach will keep you safe.

Note

Mark instance variables private.

Mark getters and setters public.

“Sadly, Bill forgot to encapsulate his Cat class and ended up with a flat cat.”

(overheard at the water cooler).

Encapsulating the GoodDog class

image with no caption

Note

Even though the methods don’t really add new functionality, the cool thing is that you can change your mind later. you can come back and make a method safer, faster, better.

Note

Any place where a particular value can be used, a method call that returns that type can be used.

instead of:

int x = 3 + 24;

you can say:

int x = 3 + one.getSize();

How do objects in an array behave?

Just like any other object. The only difference is how you get to them. In other words, how you get the remote control. Let’s try calling methods on Dog objects in an array.

  1. Declare and create a Dog array, to hold 7 Dog references.

    Dog[] pets;
    pets = new Dog[7];
    image with no caption
  2. Create two new Dog objects, and assign them to the first two array elements.

    pets[0] = new Dog();
    pets[1] = new Dog();
  3. Call methods on the two Dog objects.

    pets[0].setSize(30);
    int x = pets[0].getSize();
    pets[1].setSize(8);
    image with no caption

Declaring and initializing instance variables

You already know that a variable declaration needs at least a name and a type:

int size;
String name;

And you know that you can initialize (assign a value) to the variable at the same time:

int size = 420;
String name = "Donny";

But when you don’t initialize an instance variable, what happens when you call a getter method? In other words, what is the value of an instance variable before you initialize it?

image with no caption

Note

Instance variables always get a default value. If you don’t explicitly assign a value to an instance variable, or you don’t call a setter method, the instance variable still has a value!

integers

0

floating points

0.0

booleans

false

references

null

image with no caption

Note

You don’t have to initialize instance variables, because they always have a default value. Number primitives (including char) get 0, booleans get false, and object reference variables get null.

(Remember, null just means a remote control that isn’t controlling / programmed to anything. A reference, but no actual object.)

The difference between instance and local variables

  1. Instance variables are declared inside a class but not within a method.

    class Horse {
       private double height = 15.2;
       private String breed;
       // more code...
    }
  2. Local variables are declared within a method.

    class AddThing {
       int a;
       int b = 12;
    
       public int add() {
          int total = a + b;
          return total;
       }
    }
  3. Local variables MUST be initialized before use!

    image with no caption
image with no caption

Local variables do NOT get a default value! The compiler complains if you try to use a local variable before the variable is initialized.

Comparing variables (primitives or references)

Sometimes you want to know if two primitives are the same. That’s easy enough, just use the == operator. Sometimes you want to know if two reference variables refer to a single object on the heap. Easy as well, just use the == operator. But sometimes you want to know if two objects are equal. And for that, you need the .equals() method. The idea of equality for objects depends on the type of object. For example, if two different String objects have the same characters (say, “expeditious”), they are meaningfully equivalent, regardless of whether they are two distinct objects on the heap. But what about a Dog? Do you want to treat two Dogs as being equal if they happen to have the same size and weight? Probably not. So whether two different objects should be treated as equal depends on what makes sense for that particular object type. We’ll explore the notion of object equality again in later chapters (and Appendix B), but for now, we need to understand that the == operator is used only to compare the bits in two variables. What those bits represent doesn’t matter. The bits are either the same, or they’re not.

Note

Use == to compare two primitives, or to see if two references refer to the same object.

Use the equals() method to see if two different objects are equal.

(Such as two different String objects that both represent the characters in “Fred”)

To compare two primitives, use the == operator

The == operator can be used to compare two variables of any kind, and it simply compares the bits.

if (a == b) {...} looks at the bits in a and b and returns true if the bit pattern is the same (although it doesn’t care about the size of the variable, so all the extra zeroes on the left end don’t matter).

int a = 3;
byte b = 3;
if (a == b) { // true }
image with no caption

To see if two references are the same (which means they refer to the same object on the heap) use the == operator

Remember, the == operator cares only about the pattern of bits in the variable. The rules are the same whether the variable is a reference or primitive. So the == operator returns true if two reference variables refer to the same object! In that case, we don’t know what the bit pattern is (because it’s dependent on the JVM, and hidden from us) but we do know that whatever it looks like, it will be the same for two references to a single object.

Foo a = new Foo();
Foo b = new Foo();
Foo c = a;
if (a == b) { // false }
if (a == c) { // true }
if (b == c) { // false }
image with no caption
image with no caption

Get Head First Java, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.