More Related Content Similar to 05 object behavior (20) More from Program in Interdisciplinary Computing (20) 05 object behavior1. How Objects Behavemethods 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? 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”. 2. How Objects Behave LIS4930 © PIC You 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? Song title artist knows setTitle() setArtist() play() Sing Travis My Way Sex Pistols My Way Sinatra Sister DMB Politik Coldplay does t2 s3 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! Song Song 4. You Can Send Things To A Method LIS4930 © PIC Just 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. But here’s the important part: If a method takes a parameter, you MUST pass it something 5. LIS4930 © PIC Call the jump method on the Dog reference, and pass in the value 3 (as the argument to the method). 2 1 The bits representing the int value 3 are delivered into the bark method. argument parameter The bits land in the numOfJumps parameter (an int-sized variable). Use the numOfJumps parameter as a variable in the method code. 3 4 void jump (intnumOfJumps){ while (numOfJumps > 0) { //volunteer jumps once numOfJumps = numOfJumps – 1; } } Dog d = new Dog() d.jump(3); 6. You can get things back from a method LIS4930 © PIC 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() { } intgiveNumber () { return 42; } But, we can declare a method to give a specific type of value back to the caller, such as: 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! 7. LIS4930 © PIC You can get things back from a method 00101010 theSecret These types MUST match The bits representing 42 are returned from the giveSecret() method, and land in the variable named theSecret. int intgiveSecret ( ){ intsecretNum = 42; return secretNum; } inttheSecret = life.giveSecret( ); 8. 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: 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. Calling a two-parameter method, and sending it two arguments: If a method has parameters, you must pass arguments of the right type and order. void go( ) { TestStufft = new TestStuff( ); t.takeTwo (12, 34); } void takeTwo( intx, inty ) { intz = x + y; System.out.println(“Total is “ + z); } 9. 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. 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. 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. void go( ) { int snicker = 8; int bar = 4; t.takeTwo(snicker, bar); } void takeTwo( intx, inty ) { x = 13; intz =x / y; System.out.println(“Resultis “ + z); } 10. Java is Pass-by-Value. That Means Pass-by-copy. LIS4930 © PIC 1 2 3 4 Declare an int variable and assign it the value ‘7’. The bit pattern for 7 goes into the variable named x. 00000111 intx = 7; X int Declare a method with an int parameter named z. Z void go(intz) { } int 00000111 00000111 Call the go() method, passing the variable x as the argument. The bits in x are copied, and the copy lands in z. Z copy of x X int int foo.go(x); void go (intz); x and z aren’t connected 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. 00000111 0000000 X Z int int void go (intz) { z = 0; } 11. There are no Dumb Questions! LIS4930 © PIC 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. 12. Getters & Setters LIS4930 © PIC Now 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. ElectricGuitar brand numOfPickups rockStarUsesIt getBrand() setBrand() getNumOfPickups() setNumOfPickups() getRockStarUsesIt() setRockStarUsesIt() A Setter’s sole purpose is to take an argument value and use it to set the value of an instance variable. 13. ENCAPSULATIONCover Your Exposed Parts! LIS4930 © PIC Here we have been humming along without a care in the world leaving our data out there for anyone to see and even touch. Exposed means reachable with the dot operator, as in: theCat.height = 7; 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; 14. LIS4930 © PIC ENCAPSULATIONCover Your Exposed Parts! By forcing everybody to call a setter method, we can protect the cat from unacceptable size changes. We put in checks to guarantee a minimum cat height Cat name height color setName() getName() setHeight() getHeight() setColor()getColor() Encapsulation puts a fig leaf over the instance variables, so nobody can set them to something inappropriate. public void setHeight (int ht) { if (ht > 9) { height = ht; } } 15. Hide the Data LIS4930 © PIC 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. 16. Encapsulating the GoodDog Class LIS4930 © PIC Make 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. 17. SUMMARY LIS4930 © PIC ALL variables must have: Access Modifier (optional) Type Name Value (optional) private int kyle = 10; ALL methods must have: Access Modifier (optional) Return type Name Parameters (optional) Curly brackets public void bark(int x) { } Editor's Notes http://www.google.com/search?hl=en&client=firefox-a&rls=org.mozilla%3Aen-US%3Aofficial&hs=QUE&q=the+answer+to+life+the+universe+and+everything&btnG=Search&aq=f&oq=&aqi=g10