17
How Objects Behave methods use instance variables LIS4930 © PIC You already know that each instance of a class can have its own unique values for instance variables. Dog A can have a name “Rufus” and a weight of 70lbs. Dog B is “Killer” and weighs 9 pounds. And if the Dog class has a method makeNoise(), well, don’t you think a 70lb dog barks a bit deeper than the little 9-pounder? Rufu s Kil ler Fortunately that is 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 14lbs, make yippy sound, else…” or “increase weight by 5”.

05 object behavior

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: 05 object behavior

LIS4930 © PIC

How Objects Behavemethods use instance variables

You already know that each instance of a class can have its own unique values for instance variables. Dog A can have a name “Rufus” and a weight of 70lbs. Dog B is “Killer” and weighs 9 pounds. And if the Dog class has a method makeNoise(), well, don’t you think a 70lb dog barks a bit deeper than the little 9-pounder?Rufus

Killer

Fortunately that is 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 14lbs, make yippy sound, else…” or “increase weight by 5”.

Page 2: 05 object behavior

LIS4930 © PIC

How Objects BehaveYou already know that objects of one type can have different instance variable values. But what about the methods?

Can every object of that type have different method behavior?

t2

Song

SingTravi

s

Politik

Coldplay

Song

My WaySinatr

a

s3

My WaySex

PistolsSisterDMB

Song

knows

does

titleartist

setTitle()setArtist()play()

Calling play() on this instance will cause “Sing” to play.

Calling play() on this instance will cause “My Way” to play. But, not the Sinatra one!

Page 3: 05 object behavior

LIS4930 © PIC

The Size Affects the Bark!

Dog

name

bark()

Page 4: 05 object behavior

LIS4930 © PIC

You Can Send Things To A MethodJust as you may have done in other programming languages, you can

pass values into your methods.

A method uses parameters. A caller passes arguments.

Arguments are the things you pass into the methods. An argument lands face-down into a 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.

If a method takes a parameter, you MUST pass it something

But here’s the important part:

Page 5: 05 object behavior

LIS4930 © PIC

1 Call the jump method on the Dog reference, and pass in the value 3 (as the argument to the method).

Dog d = new Dog()d.jump(3);

void jump (int numOfJumps){while (numOfJumps

> 0) {//volunteer

jumps oncenumOfJumps

= numOfJumps – 1;}

}

2 The bits representing the int value 3 are delivered into the bark method.argument

parameter3 The bits land in the

numOfJumps parameter (an int-sized variable).

4 Use the numOfJumps parameter as a variable in the method code.

Page 6: 05 object behavior

LIS4930 © PIC

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 giveNumber () {

return 42;}If you declare a method to return a value, you must return a value

of the declared type! (Or something that is compatible with the declared type!)

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

Page 7: 05 object behavior

LIS4930 © PIC

You can get things back from a method

int giveSecret ( ){int secretNum = 42;

return secretNum;}

int theSecret = life.giveSecret( );

These types MUST match

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

001010

10

theSecret

int

Page 8: 05 object behavior

LIS4930 © PIC

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:void go( ) {

TestStuff t = new TestStuff( );

t.takeTwo (12, 34);}

void takeTwo( int x, int y ) {int z = x + y;

System.out.println(“Total is “ + z);}

The arguments you pass land in the same order you passed them. First argument lands in the first parameter, second argument in the second parameter, and so no.

Page 9: 05 object behavior

LIS4930 © PIC

You Can Send MORE Than One Thing To A Method

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

void go( ) {int snicker = 8;int bar = 4;t.takeTwo(snicker, bar);

}

void takeTwo( int x, int y ) {x = 13;int z = x / y;

System.out.println(“Result is “ + z);}

The values of snicker and bar land in the x and y parameters. So now the bits in x are identical to the bits in foo (the bit pattern for the integer ‘7’) and the bits in y are identical to the bits in bar.

What’s the value of z? It’s the same result you’d get if you divided snicker by bar at the time you passed them into the takeTwo method.

Page 10: 05 object behavior

LIS4930 © PIC

Java is Pass-by-Value. That Means Pass-by-copy.

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

int x = 7; 000001

11X

int

2Declare a method with an int parameter named z.

void go(int z) { }

Z

int

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

000001

11X

int

00000111

Z

int

copy of x

foo.go(x);

void go (int z);

4Change 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.

000001

11X

int

000000

0Z

int

void go (int z) { z = 0; }

x and z aren’t

connected

Page 11: 05 object behavior

LIS4930 © PIC

There are no Dumb Questions!

Q: What happens if the argument you want to pass is an object instead of a primitive?

A: Java passes everything by value. Everything. But value means bits inside the variable. And remember, you don’t stuff objects into variables; the variable is a remote control – a reference to an object. So if you pass a reference to an object into a method, you’re passing a copy of the remote control.

Q: Do I have to return the exact type I declared?

A: You can return anything that can be implicitly promoted to that type. But, you must use an explicit cast when the declared type is smaller than what you’re trying to return.

Page 12: 05 object behavior

LIS4930 © PIC

Getters & SettersNow that we’ve seen how parameters and return types work, it’s time to put them to good use: Getters and Setters.

Getters and Setters are methods that get and set instance variables.

A Getter’s sole purpose in life is to send back, as a return value, the value of whatever it is supposed to be Getting.A Setter’s sole purpose is to take an argument value and use it to set the value of an instance variable.

ElectricGuitar

brandnumOfPickupsrockStarUsesIt

getBrand()setBrand()getNumOfPickups()setNumOfPickups()getRockStarUsesIt()setRockStarUsesIt()

Page 13: 05 object behavior

LIS4930 © PIC

ENCAPSULATIONCover Your Exposed Parts!

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

Think about this idea of using our remote control to control the cat, and the remote getting into the hands of the wrong person. A reference variable (the remote) could be quite dangerous. Because what is to prevent:

theCat.height = 40;

Exposed means reachable with the dot operator, as in:

theCat.height = 7;

Page 14: 05 object behavior

LIS4930 © PIC

ENCAPSULATIONCover Your Exposed Parts!

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

public void setHeight (int ht) {if (ht > 9) {

height = ht;}

}

We put in checks to guarantee a minimum cat heightCat

nameheightcolor

setName()getName()setHeight()getHeight()setColor()getColor()

Encapsulation puts a fig leaf over the instance variables, so nobody can set them to something inappropriate.

Page 15: 05 object behavior

LIS4930 © PIC

Hide the Data

OK so you now know how to protect your data (instance variables) but how do you hide them?

You are already familiar with the public key word seen in every main() method; the public key word is called an access modifier and it allows anyone to access (call) that method. Well, there is another access modifier called private. Private only allows members of that very object to access its contents. So for instance, if the instance variables of an object are se to private only that object’s methods can access its instance variables!

Here’s an encapsulation starter rule-of-thumb:

Mark instance variables

private.Mark getters and setters

public.

Page 16: 05 object behavior

LIS4930 © PIC

Encapsulating the GoodDog ClassMake the instance variable private Make the getter

and setter methods public

Even though the methods can’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.

Page 17: 05 object behavior

LIS4930 © PIC

SUMMARYALL variables must have:1. Access Modifier

(optional)2. Type3. Name 4. Value (optional)

private int kyle = 10;

ALL methods must have:1. Access Modifier

(optional)2. Return type3. Name 4. Parameters (optional)5. Curly brackets

public void bark(int x) { }