### Review: Methods

• Why do Programming Languages have methods ?

• Level of abstraction:

• Low level of abstraction = (meaning) we can see a lot of details

 We can see exactly what the computer is doing and what steps the algorithm will take. When we discuss something using Java statements, we are discussing the topic at a low level

• High level of abstraction = (meaning) we can see very little detail, we look at the "big picture"

 This is the level where humans will operate when they want to solve a complex problem When we discuss something using operatios that are implemented using Java methods, we are discussing the topic at a high level

• Example: algorithm to find the median of a list of numbers

• High level discription:

 ``` 1. sort the list of numbers (= Sort(A) method) 2. find the entry in the middle of the list ```

• Low level description:

 ``` Given: a[ ] = list of numbers /* --------------------------------------------------- This is the selection sort algorithm --------------------------------------------------- */ for ( i = 0 ; i < a.length ; i ++ ) { /* --------------------------------------------------- Find array element with min. value among a[i], a[i+1], ..., a[n-1] --------------------------------------------------- */ min_j = i; // Assume elem i (a[i]) is the minimum for ( j = i+1 ; j < a.length ; j++ ) { if ( a[j] < a[min_j] ) { min_j = j; // We found a smaller minimum, update min_j } } /* --------------------------------------------------- Swap a[i] and a[min_j] --------------------------------------------------- */ help = a[i]; a[i] = a[min_j]; a[min_j] = help; } /* Median = the middle element in sorted array */ int mid = a.length/2; System.out.print( a[ mid ] ); ```

• Reason for methods:

 Methods are used to encapsulate (put in a capsule) helpful operations that are used to solve problems Methods help humans solve complex problems using a computer (by enabling human to think and solve problems at a higher abstraction level)

• Blackbox concept

• Blackbox:

 Blackbox = a device for which we have no knowledge (or we do not care/worry about) of the exact (internal) operation We only know what some blackbox does (i.e., we know its functionality), but we do not know the internal mechanism of the blackbox (i.e., we cannot (or do not care to) open the blackbox)

• Fact:

 Most Java programmers use methods in the Java library as blackboxes

• Case in point:

 Every student has used the System.out.print() method to print variables in their Java program I have not yet met a student that has studied the internal statements of this method... (For the curious, here is an article: click here )

• Evolution of the "method" concept

• Originally: (we called them subroutine, procedure, function)

 Subroutines/procedures encapsulated only computatations (= statements) into a black box

• Around 1967:

• A programming language was developed for write computer simulations called Simula 67

 Simula 67 is considered the first object-oriented programming language. As its name implies, Simula was designed for doing simulations, and the needs of that domain (methods used by computer simulation require a lot of information (= variables)) provided the framework for many of the features of object-oriented languages today. Wikipedia page: click here

• Object-Oriented Programming (OOP):

• Methods still encapsulate statements

• We add another layer of encapsulation called: class

• A class encapsulates (contains as one unit):

 data fields --- contains essential information used by the methods in the class Methods = define operations on the data fields in the class

• Object-Oriente Programming Language:

• Programming languages that provide language features that allow programmers to encapsulate

 data,        and          methods

in one program unit are called object-oriented programming languages

(Java is an Object-Oriented Programming language since the class construct of Java can do this)

• Life without method

• Fact:

 Methods are not necessary for writting programs However, your life as a programmer would be very difficult without methods.....

• Would you want to write programs like this:

 ``` public static void main(String[] args) { int sum; sum = 0; for (int i = 1; i <= 10; i++) { sum += i; } System.out.println("The sum of 1-10 is: " + sum); sum = 0; for (int i = 25; i <= 30; i++) { sum += i; } System.out.println("The sum of 25-30 is: " + sum); sum = 0; for (int i = 40; i <= 50; i++) { sum += i; } System.out.println("The sum of 40-50 is: " + sum); } ```

Or rather like this:

 ``` public static void main(String[] args) { System.out.println("sum(1, 10) is: " + sum(1,10) ); System.out.println("sum(25, 30) is: " + sum(25,30) ); System.out.println("sum(40, 50) is: " + sum(40,50) ); } ```

• Fact:

 Methods are not necessary You can re-write any program that does not use methods by replacing each method invacation by the entire body of the method

• Defining a Method

• Syntax:

 ``` access-specifier [static] return-DataType methodName( list-of-parameters ) { body (local variables + statements) } ```

• Example:

 ``` public class ReviewJava { public static int sum( int start, int end ) { int s; s = 0; for ( int i = start; i <= end; i++ ) { s += i; } return s; } } ```

• Call/invoke (run) a method

• Syntax:

 ``` Class method (static) ClassName.methodName( actual-parameters ) Instance method (no static) instanceVariable.methodName( actual-parameters ) ```

• Example:

 ``` public class testProg1 { public static void main(String[] args) { int x; x = ReviewJava.sum(1, 10); System.out.println("sum(1, 10) is: " + x ); System.out.println("sum(25, 30) is: " + ReviewJava.sum(25,30) ); } } ```

• Example Program: (Demo above code)

How to run the program:

 Right click on link(s) and save in a scratch directory To compile:   javac testProg1.java To run:          java testProg1

• Nomenclature

• The method definition consists of 2 main parts:

• These are the names of the different parts of a method definition:

• Invoking a method:

• Facts:

• Method header contains all te necessary information for the Java compiler to use the method:

 Access specifier tells the Java compiler where the method can be invoked Class (static) modifier tells the Java compiler if methods needs a instance parameter variable Return data type tells the Java compiler how to convert the encoding scheme (if the receiving variable is of a different data type) Method name and parameters tells the Java compiler how to identify a method (inside a class) Parameter data types tells the Java compiler how to convert the encoding scheme (if the actual parameter variables is of a different data type)

• Method body contains

 Local variables that only exist while the method is running Statements (actions) that perform the tasks carried out by the method

• Method signature

• Definition:

 Signature of a method = the name of the method plus the data types of the parameters of the method

Example:

• Fact:

 A class can contain multiple methods that has the same method name

 Overloaded method (name) = when multiple methods in the same class has the same method name

Example:

 ``` public class MyClass { public static void meth( ) { System.out.println("Running: meth( ) "); } public static void meth( int x ) { System.out.println("Running: meth( int x ) "); } public static void meth( double x ) { System.out.println("Running: meth( double x ) "); } public static void meth( int x, int y ) { System.out.println("Running: meth( int x, int y ) "); } public static void meth( double x, double y ) { System.out.println("Running: meth( double x, double y ) "); } } ```

• Identifying a method to invoke

• How does Java tell which overloaded method to use:

• Overloaded methods are differentiated by:

 the number of the arguments     and           the type of the arguments

passed into the method.

In other words:

 Overloaded methods are differentiated by their signature

• Example:

 ``` public class Methods1 { public static void main(String[] args) { int a = 1; double b = 1; MyClass.meth(); // meth( ) MyClass.meth( a ); // meth( int ) MyClass.meth( b ); // meth( double ) MyClass.meth( 1 ); // meth( int ) MyClass.meth( 1.0 ); // meth( double ) MyClass.meth( a, a ); // meth( int, int ) MyClass.meth( b, b ); // meth( double, double ) MyClass.meth( 1, 1 ); // meth( int, int ) MyClass.meth( 1.0, 1.0 ); // meth( double, double ) } } ```

Output:

 ``` Running: meth( ) Running: meth( int x ) Running: meth( double x ) Running: meth( int x ) Running: meth( double x ) Running: meth( int x, int y ) Running: meth( double x, double y ) Running: meth( int x, int y ) Running: meth( double x, double y ) ```

• Automatic conversion rules and method signature

• Fact:

 If there is no method in a class that matches the method signature, the Java compiler will use automatic conversion rules to try to find a "fitting" method

Example:

 ``` MyClass.meth( a, b ); // Signature: meth( int, double ) // Matching method: // meth( double x, double y ) ```

• Example Program: (Demo above code)

How to run the program:

 Right click on link(s) and save in a scratch directory To compile:   javac Methods1.java To run:          java Methods1

• Warning: do not create too many overloaded methods !!!

• Warning:

 Overloaded method can confuse the Java compiler Sometimes, Java may not be able to distinguish overloaded methods

Example:

 ``` public class MyClass2 { public static void meth( int x, double y ) { System.out.println("Running: meth( int, double ) "); } public static void meth( double x, int y ) { System.out.println("Running: meth( double, int ) "); } } ```

The call MyClass2.meth( int, int ) cannot be resolved:

 ``` public class Methods2 { public static void main(String[] args) { int a = 1; double b = 1; MyClass2.meth( a, a ); // meth( int, int ) ??? } } ```

This is the output of the Java compiler:

 ```Methods2.java:8: reference to meth is ambiguous, both method meth(int,double) in MyClass2 and method meth(double,int) in MyClass2 match MyClass2.meth( a, a ); // meth( int, int ) ??? ^ 1 error ```

• Example Program: (Demo above code)

How to run the program:

 Right click on link(s) and save in a scratch directory To compile:   javac Methods2.java You should see the above error message