Methods: Why use methods 2 types of methods: class, instance Steps in using methods Example 1 on defining and using method: min **** Example 2 on defining and using method: GCD not good, need local variable !!! Defining a class method - syntax -------------- Concept: parameter variable or formal parameter 1. defined/created when a method is invoked 2. value of parameter variable is initialized using the values of the actual parameter Invoking a class method - behind the scene 1. value of the actual parameter is copied into formal parameter variables 2. flow of control is transfered to called method 3. flow of control is transfered back only upon return 4. Upon return, the method call is replaced by the value returned Method returns: 1. by executing a "return" statement 2. when it reach the end of the method definition (in this case, it returns no value) =========================================================== Concept: modular programming A method is a "self-contained" unit that performed a well-defined task A method usually implements an algorithm After a method is written, any user can use it WITHOUT knowing the exact steps of the algorithm ---- Method hides the details ---- help to make thinking and problem solving more holostic Making self-contained execution units: local variables - 1. created each time a method is invoked 2. destroyed when a method returns. scope of variables method() { { int i; } { int i; } } Example: Example 1 on modular programming: GCD Example 2 on modular programming: LCM Example 3 on modular programming: IsPrime for i = 2, i <= n/2 ; i++ if ( n % i == 0 ) return (false) return(true); ======================================================================= Parameter passing mechanism: 1. pass by value ======================================================================= Implementing method invocation: call stack 1. Find all prime number between 2 to n Method calls IsPrime(k) ======================================================================= Overloading method name ======================================================================= Building Library of methods: Math Random() method ======================================================================= Delay this for later: Step-wise refinement Top-down design divide and conquer Case study: text formatting