Chapter 4. How Objects Behave: Methods Use Instance Variables
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?
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. When you call the play() method on an the instance, it will play the song represented by the value of the title and artist instance variables for that instance. So, if you call the play() method on one instance, youâll hear the song âHavanaâ by Cabello, while another instance plays âSingâ by Travis. The method code, however, is the same.
void play() { soundPlayer.playSound(title, artist); }
Song song1 = new Song(); song1.setArtist("Travis"); song1.setTitle("Sing"); Song song2 = new Song(); song2.setArtist("Sex Pistols"); song2.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.
class Dog { int size; String name; void bark() { if (size > 60) { System.out.println("Wooof! Wooof!"); } else if (size > 14) { System.out.println("Ruff! Ruff!"); } else { System.out.println("Yip! Yip!"); } } }
class DogTestDrive { public static void main(String[] args) { Dog one = new Dog(); one.size = 70; Dog two = new Dog(); two.size = 8; Dog three = new Dog(); three.size = 35; one.bark(); two.bark(); three.bark(); } }
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 caller passes arguments. A method takes parameters.
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 when you call it. And that something must be a value of the appropriate type.
You can get things back from a method
Methods can also 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.)
Whatever you say youâll give back, you better give back!
The compiler wonât let you return the wrong type of thing.
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
You can pass variables into a method, as long as the variable type matches the parameter type
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: letâs create 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 a common 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.
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; } }
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.
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:
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.
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.
âSadly, Bill forgot to encapsulate his Cat class and ended up with a flat cat.â
(overheard at the water cooler)
Java Exposed
This weekâs interview: An Object gets candid about encapsulation.
HeadFirst: Whatâs the big deal about encapsulation?
Object: OK, you know that dream where youâre giving a talk to 500 people when you suddenly realize youâre naked?
HeadFirst: Yeah, weâve had that one. Itâs right up there with the one about the Pilates machine and...no, we wonât go there. OK, so you feel naked. But other than being a little exposed, is there any danger?
Object: Is there any danger? Is there any danger? [starts laughing] Hey, did all you other instances hear that, âIs there any danger?â he asks? [falls on the floor laughing]
HeadFirst: Whatâs funny about that? Seems like a reasonable question.
Object: OK, Iâll explain it. Itâs [bursts out laughing again, uncontrollably]
HeadFirst: Can I get you anything? Water?
Object: Whew! Oh boy. No Iâm fine, really. Iâll be serious. Deep breath. OK, go on.
HeadFirst: So what does encapsulation protect you from?
Object: Encapsulation puts a force-field around my instance variables, so nobody can set them to, letâs say, something inappropriate.
HeadFirst: Can you give me an example?
Object: Happy to. Most instance variable values are coded with certain assumptions about their boundaries. Like, think of all the things that would break if negative numbers were allowed. Number of bathrooms in an office. Velocity of an airplane. Birthdays. Barbell weight. Phone numbers. Microwave oven power.
HeadFirst: I see what you mean. So how does encapsulation let you set boundaries?
Object: By forcing other code to go through setter methods. That way, the setter method can validate the parameter and decide if itâs doable. Maybe the method will reject it and do nothing, or maybe itâll throw an Exception (like if itâs a null Social Security number for a credit card application), or maybe the method will round the parameter sent in to the nearest acceptable value. The point is, you can do whatever you want in the setter method, whereas you canât do anything if your instance variables are public.
HeadFirst: But sometimes I see setter methods that simply set the value without checking anything. If you have an instance variable that doesnât have a boundary, doesnât that setter method create unnecessary overhead? A performance hit?
Object: The point to setters (and getters, too) is that you can change your mind later, without breaking anybody elseâs code! Imagine if half the people in your company used your class with public instance variables, and one day you suddenly realized, âOopsâthereâs something I didnât plan for with that value, Iâm going to have to switch to a setter method.â You break everyoneâs code. The cool thing about encapsulation is that you get to change your mind. And nobody gets hurt. The performance gain from using variables directly is so miniscule and would rarelyâif everâbe worth it.
Encapsulating the GoodDog class
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.
Declare and create a Dog array to hold seven Dog references.
Dog[] pets; pets = new Dog[7];
Create two new Dog objects, and assign them to the first two array elements.
pets[0] = new Dog(); pets[1] = new Dog();
Call methods on the two Dog objects.
pets[0].setSize(30); int x = pets[0].getSize(); pets[1].setSize(8);
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?
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
Instance variables are declared inside a class but not within a method.
class Horse { private double height = 15.2; private String breed; // more code... }
Local variables are declared within a method.
Local variables MUST be initialized before use!
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; for example, you might want to check an int result with some expected integer value. 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; for example, is this Dog object exactly the same Dog object I started with? 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, âmy nameâ), 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, 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.
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 all the extra zeros on the left end donât matter).
int a = 3; byte b = 3; if (a == b) { // true }
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.
(E.g., two different String objects that both contain the characters âFredâ)
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
Exercise
BE the Compiler
Each of the Java files on this page represents a complete source file. Your job is to play compiler and determine whether each of these files will compile. If they wonât compile, how would you fix them, and if they do compile, what would be their output?
A
class XCopy { public static void main(String[] args) { int orig = 42; XCopy x = new XCopy(); int y = x.go(orig); System.out.println(orig + " " + y); } int go(int arg) { arg = arg * 2; return arg; } }
B
class Clock { String time; void setTime(String t) { time = t; } void getTime() { return time; } } class ClockTestDrive { public static void main(String[] args) { Clock c = new Clock(); c.setTime("1245"); String tod = c.getTime(); System.out.println("time: "+tod); } }
Answers in âBE the Compilerâ.
A bunch of Java components, in full costume, are playing a party game, âWho am I?â They give you a clue, and you try to guess who they are, based on what they say. Assume they always tell the truth about themselves. If they happen to say something that could be true for more than one attendee, then write down all for whom that sentence applies. Fill in the blanks next to the sentence with the names of one or more attendees.
Who Am I?
Tonightâs attendees:
instance variable, argument, return, getter, setter, encapsulation, public, private, pass by value, method
A class can have any number of these. | __________________________________ |
A method can have only one of these. | __________________________________ |
This can be implicitly promoted. | __________________________________ |
I prefer my instance variables private. | __________________________________ |
It really means âmake a copy.â | __________________________________ |
Only setters should update these. | __________________________________ |
A method can have many of these. | __________________________________ |
I return something by definition. | __________________________________ |
I shouldnât be used with instance variables. | __________________________________ |
I can have many arguments. | __________________________________ |
By definition, I take one argument. | __________________________________ |
These help create encapsulation. | __________________________________ |
I always fly solo. | __________________________________ |
Answers in âWho Am I?â.
Mixed Messages
A short Java program is listed to your right. Two blocks of the program are missing. Your challenge is to match the candidate blocks of code (below) with the output that youâd see if the blocks were inserted.
Not all the lines of output will be used, and some of the lines of output might be used more than once. Draw lines connecting the candidate blocks of code with their matching command-line output.
Answers in âMixed Messagesâ.
Pool Puzzle
Your job is to take code snippets from the pool and place them into the blank lines in the code. You may not use the same snippet more than once, and you wonât need to use all the snippets. Your goal is to make a class that will compile and run and produce the output listed.
Answers in âPool Puzzleâ.
Output
public class Puzzle4 { public static void main(String [] args) { ___________________________________ int number = 1; int i = 0; while (i < 6) { ___________________________ ___________________________ number = number * 10; _________________ } int result = 0; i = 6; while (i > 0) { _________________ result = result + ___________________ } System.out.println("result " + result); } } class ___________ { int intValue; ________ ______ doStuff(int _________) { if (intValue > 100) { return _________________________ } else { return _________________________ } } }
Note
Note: Each snippet from the pool can be used only once!
Five-Minute Mystery
When Buchanan roughly grabbed Jaiâs arm from behind, Jai froze. Jai knew that Buchanan was as stupid as he was ugly and he didnât want to spook the big guy. Buchanan ordered Jai into his bossâs office, but Jaiâd done nothing wrong (lately), so he figured a little chat with Buchananâs boss Leveler couldnât be too bad. Heâd been moving lots of neural-stimmers in the west side lately, and he figured Leveler would be pleased. Black market stimmers werenât the best money pump around, but they were pretty harmless. Most of the stim-junkies heâd seen tapped out after a while and got back to life, maybe just a little less focused than before.
Levelerâs âofficeâ was a skungy-looking skimmer, but once Buchanan shoved him in, Jai could see that itâd been modified to provide all the extra speed and armor that a local boss like Leveler could hope for. âJai my boy,â hissed Leveler, âpleasure to see you again.â âLikewise Iâm sure...,â said Jai, sensing the malice behind Levelerâs greeting, âWe should be square Leveler, have I missed something?â âHa! Youâre making it look pretty good, Jai. Your volume is up, but Iâve been experiencing, shall we say, a little âbreachâ lately,â said Leveler.
Jai winced involuntarily; heâd been a top drawer jack-hacker in his day. Anytime someone figured out how to break a street-jackâs security, unwanted attention turned toward Jai. âNo way itâs me man,â said Jai, ânot worth the downside. Iâm retired from hacking, I just move my stuff and mind my own business.â âYeah, yeah,â laughed Leveler, âIâm sure youâre clean on this one, but Iâll be losing big margins until this new jack-hacker is shut out!â âWell, best of luck, Leveler. Maybe you could just drop me here and Iâll go move a few more âunitsâ for you before I wrap up today,â said Jai.
âIâm afraid itâs not that easy, Jai. Buchanan here tells me that word is youâre current on Java NE 37.3.2,â insinuated Leveler. âNeural edition? Sure, I play around a bit, so what?â Jai responded, feeling a little queasy. âNeural editionâs how I let the stim-junkies know where the next drop will be,â explained Leveler. âTrouble is, some stim-junkieâs stayed straight long enough to figure out how to hack into my Warehousing database.â âI need a quick thinker like yourself, Jai, to take a look at my StimDrop Java NE class; methods, instance variables, the whole enchilada, and figure out how theyâre getting in. It should...,â âHEY!â exclaimed Buchanan, âI donât want no scum hacker like Jai nosinâ around my code!â âEasy big guy,â Jai saw his chance, âIâm sure you did a top rate job with your access modi...â âDonât tell me, bit twiddler!â shouted Buchanan, âI left all of those junkie-level methods public so they could access the drop site data, but I marked all the critical WareHousing methods private. Nobody on the outside can access those methods, buddy, nobody!â
âI think I can spot your leak, Leveler. What say we drop Buchanan here off at the corner and take a cruise around the block?â suggested Jai. Buchanan clenched his fists and started toward Jai, but Levelerâs stunner was already on Buchananâs neck, âLet it go, Buchanan,â sneered Leveler, âKeep your hands where I can see them and step outside. I think Jai and I have some plans to make.â
What did Jai suspect?
Will he get out of Levelerâs skimmer with all his bones intact?
Answers in âFive-Minute Mysteryâ.
Exercise Solutions
Sharpen your pencil
(from âSharpen your pencilâ)
BE the Compiler
(from âBE the Compilerâ)
Class âXCopyâ compiles and runs as it stands! The output is: â42 84â. Remember, Java is pass by value, (which means pass by copy), and the variable âorigâ is not changed by the go( ) method.
Who Am I?
(from âWho Am I?â)
A class can have any number of these. | instance variables, getter, setter, method |
A method can have only one of these. | return |
This can be implicitly promoted. | return, argument |
I prefer my instance variables private. | encapsulation |
It really means âmake a copy.â | pass by value |
Only setters should update these. | instance variables |
A method can have many of these. | argument |
I return something by definition. | getter |
I shouldnât be used with instance variables | public |
I can have many arguments. | method |
By definition, I take one argument. | setter |
These help create encapsulation. | getter, setter, public, private |
I always fly solo. | return |
Puzzle Solutions
Pool Puzzle
(from âPool Puzzleâ)
public class Puzzle4 { public static void main(String[] args) { Value[] values = new Value[6]; int number = 1; int i = 0; while (i < 6) { values[i] = new Value(); values[i].intValue = number; number = number * 10; i = i + 1; } int result = 0; i = 6; while (i > 0) { i = i - 1; result = result + values[i].doStuff(i); } System.out.println("result " + result); } } class Value { int intValue; public int doStuff(int factor) { if (intValue > 100) { return intValue * factor; } else { return intValue * (5 - factor); } } }
Output
Five-Minute Mystery
(from âFive-Minute Mysteryâ)
What did Jai suspect?
Jai knew that Buchanan wasnât the sharpest pencil in the box. When Jai heard Buchanan talk about his code, Buchanan never mentioned his instance variables. Jai suspected that while Buchanan did in fact handle his methods correctly, he failed to mark his instance variables private.
That slip-up could have easily cost Leveler thousands.
Mixed Messages
(from âMixed Messagesâ)
Get Head First Java, 3rd 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.