Introduction: 5.6.0

  • procedural abstraction allows us to name a block of code as a method and call it whenever needed
    • abstracts away the details of the method
    • organizes code by function
    • reduces complexity and aids in debugging
    • allows you to reuse code

Steps in creating and calling a method

  1. declare an object of your class
  2. whenever you want to use a method, call objectReference.methodName()
  3. Write the method’s header and body in the class below
public void methodName() {  // header
  // body
}

Parameters: 5.6.1

  • methods can take parameters for data used in the method
  • variables defined in the method header are formal parameters
    • when the method is called, the values passed in are arguments
      • also called actual parameters
  • method signature or method header defines the method name, number of arguments, and data types for those arguments and return type
  • java uses call by value
    • a copy of the value of the argument is saved in the parameter
      • if the local variable is changed, this doesn’t effect the external variable
    • because object variables are references to objects in memory, this copy will refer to the same object!
      • this way large objects aren’t copied between methods
      • It is good practice not to modify mutable objects passed as parameters, with exceptions
        • the method should specify if it does this
  • methods can return values
    • the caller should capture and do something with this value
      • print it or save it in a variable
// run a motor with a set speed

/**
* Set the motor speed
* @param speed percent output (-1.0 to 1.0)
*/
public void set(double speed) {
  talon.set(speed);
}

Summary: 5.6.3

  • procedural abstraction reduces complexity and repetition of code
    • name a block of code as a method; call it whenever we need it
      • abstracts how that block works
  • Methods break large problems into subproblems, where each method solves a subproblem
  • to write methods:
    • write a method definition
      • with a method signature
    • write a method body
  • to call an object’s method, use the object name and the dot operator
  • when you call a method, you pass in arguments or actual parameters
    • these are saved in local formal parameters
  • values provided in arguments of a method call need to be in the same order as the parameters in the method signature
  • when parameters are primitive types, the formal parameters are copies of those values
    • Object types reference the same object which is passed in
      • It is good practice to not modify this object, unless otherwise specified