Methods Complexity n n The programmers biggest adversary
Methods
Complexity n n The programmer's biggest adversary is complexity Primitive types and the basic statements (assignment, while, if, etc. ) are theoretically enough to perform any computation Everything else in Java is designed to organize actions and data in order to control complexity In particular, we try to organize everything into relatively small, independent parts, with few interactions among them 2
Why objects? n n Object-oriented programming models the world as a collection of “objects” This organization: n n n allows us to think about one object at a time allows us to use pre-written objects It works best when the objects are relatively independent, rather than deeply intertwined 3
A fruity analogy n Programs can be like pomegranates—all wrapped up together and impossible to get to one part without disturbing many other parts n n Programs can be like grapes— each part is complete in itself, and only loosely connected to the other parts Grapes are better 4
Why methods? n There are two main reasons for using methods: 1. Objects have behaviors, and we try to have each method perform one behavior 2. Methods are also a way of breaking a complex behavior down into simpler components (“Divide and conquer”) 5
Modeling behaviors: Example 1 class Animal { int hunger = 10; int fatigue = 10; void eat() { hunger--; } void sleep() { fatigue = 0; } void hide() {. . . } n } When you define methods, you are defining a vocabulary with which to talk about your problem 6
Modeling behaviors: Example 2 class Document { String text; boolean saved; void open() {. . . } void save() {. . . } void edit() {. . . } } 7
Divide and conquer: Example 1 class Animal {. . . void eat() { Food f = find. Food(); chew(f); swallow(f); digest(f); } } 8
Divide and conquer: Example 2 class Document {. . . void open(File in. File) { String file. Name = ask. User. For. Name(); if (file. Exists(file. Name)) { load. File(file. Name); saved = true; } else complain. To. User(); } } 9
When do you write a method? n Write a new method: n If there is a particular behavior of an object that you need to implement n n To break a complex problem into simpler parts n n n Typically, methods like this are used from outside, to communicate something to the object The new methods should each perform a single, clearly defined task Typically, these “sub-methods” are not made available outside the class To do the same thing in more than one place n It’s always a bad idea to copy code 10
Kinds of methods n There are two kinds of methods: n instance methods (the default kind) n n n Can only be executed by an individual object May use this May use class variables and class methods May use its own instance variables and other instance methods class methods (denoted by the keyword static) n n Executed by the class itself, not by an object May not use this (why not? ) May use class variables and class methods May not use instance variables or instance methods (why not? ) 11
A common error n class Test { int fudge = 0; fudge is an instance (not static) variable—each object of type Test will have its own copy, but the class itself does not public static void main(String args[]) { System. out. println(fudge); } This means the class does the } work, not any particular object n non-static variable fudge cannot be referenced from a static context 12
When to make a method static n Instance methods are more “capable” than static methods—they can access their own instance variables and methods, as well as class variables and methods n n They are intended to be used by instances (=objects) Class (static) methods can only access class variables and methods n n They are appropriate when what you are doing does not depend on any particular object If a method never makes use of the instance variables or instance methods of the object, it should probably be static 13
Examples of static methods n You’re tired of writing System. out. println, so you write this method: static void println(String s) { System. out. println(s); } n You want to perform a task that isn’t specific to the individual object static int next. Card() { return random. next. Int(10) + 1; } 14
Defining a method n A method has the syntax: return-type method-name ( formal-parameters ) { method-variables code } n Example: int add ( int number 1, int number 2 ) { int sum = number 1 + number 2; return sum; } 15
Information flow n We call a method like this: result = add( 3 , 5 ) ; Actual parameter values are copied into formal parameters int add ( int number 1, int number 2 ) { int sum = number 1 + number 2 ; return sum ; } A result is returned Formal parameters are used 16
Formal parameters n n n int add ( int number 1, int number 2 ) { int sum = number 1 + number 2; return sum; } When you enter a method, the formal parameters are created and assigned initial values You must specify the types of the formal parameters The formal parameters are variables that you can use however you like When the method returns, the formal parameters are discarded 17
Method variables n n n int add ( int number 1, int number 2 ) { int sum = number 1 + number 2; return sum; } Within a method, you may create additional variables You can use these variables within the method When the method returns, the variables are discarded Formal parameters get their values from “outside”, method variables are created “inside, ” but they are otherwise alike 18
Primitive parameters are copied in int m = 3; int n = 5; result = add( m , n ) ; The values of m and n (that is, 3 and 5) are copied to the formal parameters int add ( int number 1 , int number 2 ) { while (number 1 > 0) { number 1 --; Changing number 1 and number 2++; number 2 does not affect m and n } return number 2 ; } The value of number 2 is returned, but the variable • This is call by value number 2 is thrown away 19
Objects are different Person p = new Person("John"); Person p actually allocates space to hold a reference to a Person new Person("John") allocates space for the actual Person, and initializes it p: "John" The assignment makes p refer to the new Person 20
Object references are copied in Person p = new Person("John"); change. Name( p ); p holds a reference to a Person "John" "Jack" void change. Name(Person per ) { per. name == "Jack"; } It is the reference that is copied in, not the Person • This means that p and per refer to the same object! • p is not changed, but changes made to the object referenced by per remain changed when the method returns. • This is call by reference 21
Assignments n n When using a method, values are assigned to the formal parameters Normal assignment statements work the same way n n n int m = 5; int n; n = m; // the value 5 is copied from m to n Person p 1 = new Person("John"); Person p 2; p 2 = p 1; // the reference is copied from p 1 to p 2 Hence, p 1 and p 2 are different names for the same Person; changes made to one change the other 22
Object references are copied in Person p = new Person("John"); change. Name( p ); "John" "Jack" void change. Name(Person per ) { per. name = "Jack"; per = new Person("Mary"); } • Changes made to the object referenced by per remain changed when the method returns. • But changes to per itself are not copied back; p still refers to the “Jack” object • This is call by reference "Mary" 23
Using instance methods I n n n You don’t call a method, you send a message to an object Suppose I know about an object john that is an instance of class Person Suppose further that the Person class has an instance method go. Away() I can tell john to go away like this: john. go. Away(); Notice that I say who I’m talking to, and what message I want to convey This is always the form: the object, a dot, then the message 24
Using instance methods II n n Suppose I want to tell john to read a book I also need to say which book n n n n This is additional information Additional information is provided by actual parameters I can do this: john. read. Book("Moby Dick"); The form is: object. message (actual-parameters) Suppose I want to tell john to kiss someone I can do this: john. kiss(mary); Is mary affected by this? n Yes! A reference to the mary object is passed to kiss 25
Using instance methods III n Suppose I want to tell myself to do something n n n (I’m pretending to be an object of type Person) I refer to myself by using the keyword this I can talk to myself like this: this. read. Book("Mirror Dance"); n Or, as a convenience, I can leave out the explicit reference to myself: read. Book("Mirror Dance"); n That is, any object can use its own methods and variables (the ones declared by its class) without explicitly naming itself 26
Using class methods I n n If a method is a class method, any object of that class can refer to it directly, without using this Example: 1. 2. class Dumb. Example { static void println(String s) { // class method System. out. println(s); } void do. Something( ) { // instance method, . . . // in the same class println("I did it!"); } } 27
Using class methods II n To use a class method from outside the class, you can send a message to the class n Examples: x = Math. abs(y); Dumb. Example. println("I can do it too"); System. out. println("So that's what this means!"); 28
Vocabulary n n n instance method – a method that can only be executed by objects (instances) of a class method – a method that can be executed by the class itself actual parameter – a value given to a method formal parameter – a variable used by a method to refer to the value it has been given call by value – to copy the value of an actual parameter into a formal parameter call by reference – to copy the reference to an object from the actual parameter into the formal parameter 29
The End 30
- Slides: 30