Document Sample
methods Powered By Docstoc
• The programmer's biggest adversary is
• 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
              Why objects?
• Object-oriented programming models the
  world as a collection of ―objects‖
• This organization:
  – 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
               Why methods?
•    There are two main reasons for using
    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‖)
Modeling behaviors: Example 1

 class Animal {
    int hunger = 10;
    int fatigue = 10;

     void eat() { hunger--; }
     void sleep() { fatigue = 0; }
     void hide() { ... }
Modeling behaviors: Example 2

class Document {
   String text;
   boolean saved;

    void open() { ... }
    void save() { ... }
    void edit() { ... }
Divide and conquer: Example 1

class Animal {
    void eat() {
       Food f = findFood();
Divide and conquer: Example 2

class Document {
    void open(File inFile) {
       String fileName = askUserForName();
       if (fileExists(fileName)) {
           saved = true;
       else complainToUser();
  When do you write a method?
• Write a new method:
  – If there is a particular behavior of an object that
    you need to implement
     • Typically, methods like this are used from outside,
       to communicate something to the object
  – To break a complex problem into simpler parts
     • The new methods should each perform a single,
       clearly defined task
     • Typically, these ―sub-methods‖ are not made
       available outside the class
                Kinds of methods
• There are two kinds of methods:
   – instance methods (the default kind)
      •   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)
      •   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?)
                 A common error
                          fudge is an instance (not static)
• class Test {            variable—each object of type Test
                          will have its own copy, but the
     int fudge = 0;
                          class itself does not
     public static void main(String args[]) {
  }                         This means the class does the
                            work, not any particular object
• non-static variable fudge cannot be referenced from
  a static context
  When to make a method static
• Instance methods are more ―capable‖ than static
  methods—they can access their own instance
  variables and methods, as well as class variables
  and methods
   – They are intended to be used by instances
• Class (static) methods can only access class
  variables and methods
   – They are appropriate when what you are doing does not
     depend on any particular object
     Examples of static methods
• You’re tired of writing System.out.println, so
  you write this method:
     static void println(String s) {
• You want to perform a task that isn’t specific to
  the individual object
     int nextCard() {
           return random.nextInt(10) + 1;
   —I didn’t make this static, but I should have!
             Defining a method
• A method has the syntax:
    return-type method-name ( formal-parameters ) {
• Example:
    int add ( int number1, int number2 ) {
       int sum = number1 + number2;
       return sum;
              Information flow
                                Actual parameter
• We call a method like this:   values are copied into
    result = add( 3 , 5 ) ;     formal parameters

    int add ( int number1, int number2 ) {

        int sum = number1 + number2 ;
        return sum ;
    }                           Formal parameters
                                are used
        A result is returned
             Formal parameters
• int add ( int number1, int number2 ) {
     int sum = number1 + number2;
     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
               Method variables
• int add ( int number1, int number2 ) {
     int sum = number1 + number2;
     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
Primitive parameters are copied in
   int m = 3;                 The values of m and n (that
   int n = 5;                 is, 3 and 5) are copied to the
   result = add( m , n ) ;    formal parameters

   int add ( int number1 , int number2 ) {
      while (number1 > 0) {
         number2++;       Changing number1 and
      }                   number2 does not affect m and n
      return number2 ;
   }                       The value of number2 is
                           returned, but the variable
• This is call by value    number2 is thrown away
           Objects are different
 Person p = new Person("John");

Person p actually allocates space   p:
to hold a reference to a Person

new Person("John") allocates             "John"
space for the actual Person, and
initializes it

The assignment makes p
refer to the new Person
Object references are copied in
                                           p holds a reference
Person p = new Person("John");
                                           to a Person
changeName( p );

void changeName(Person per ) { = "Jack"; = "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
• When using a method, values are assigned to the
  formal parameters
• Normal assignment statements work the same way
   – int m = 5;
     int n;
     n = 5; // the value 5 is copied from m to n
   – Person p1 = new Person("John");
     Person p2;
     p2 = p1; // the reference is copied from p1 to p2
• Hence, p1 and p2 are different names for the same
  Person; changes made to one change the other
  Object references are copied in
  Person p = new Person("John");
  changeName( p );

  void changeName(Person per ) { = "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
       Using instance methods I
• 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 goAway()
• I can tell john to go away like this: john.goAway();
• 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
       Using instance methods II
• Suppose I want to tell john to read a book
• I also need to say which book
    – This is additional information
    – Additional information is provided by actual parameters
•   I can do this: john.readBook("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?
    – Yes! A reference to the mary object is passed to kiss
     Using instance methods III
• Suppose I want to tell myself to do something
   – (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.readBook("Mirror Dance");
• Or, as a convenience, I can leave out the explicit
  reference to myself:
     readBook("Mirror Dance");
• That is, any object can use its own methods and
  variables (the ones declared by its class) without
  explicitly naming itself
         Using class methods I
• If a method is a class method, any object of that
  class can refer to it directly, without using this
• Example:
     class DumbExample {
        static void println(String s) { // class method
        void doSomething( ) { // instance method,
            ...                   // in the same class
            println("I did it!");
        Using class methods II
• To use a class method from outside the class,
  you can send a message to the class
  – Examples:
      x = Math.abs(y);
      DumbClass.println("I can do it too");
      System.out.println("So that's what this means!");
• instance method – a method that can only be executed by
  objects (instances) of a class
• class method – a method that can be executed by the class
• 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
The End

Shared By: