java programming: from problem analysis to program design, 4e

89
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods

Upload: jered

Post on 23-Feb-2016

38 views

Category:

Documents


0 download

DESCRIPTION

Java Programming: From Problem Analysis to Program Design, 4e. Chapter 7 User-Defined Methods. Chapter Objectives. Learn about user-defined methods Learn how to construct and use user-defined void methods in a program Actual and formal parameters - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Java Programming: From Problem Analysis to Program Design, 4e

Java Programming: From Problem Analysis to Program Design, 4e

Chapter 7User-Defined Methods

Page 2: Java Programming: From Problem Analysis to Program Design, 4e

2Java Programming: From Problem Analysis to Program Design, 4e

Chapter Objectives

• Learn about user-defined methods– Learn how to construct and use user-defined

void methods in a program– Actual and formal parameters– Explore how to construct and use a value-

returning• Explore using variables as parameters• Explore using arrays as parameters.

Page 3: Java Programming: From Problem Analysis to Program Design, 4e

3Java Programming: From Problem Analysis to Program Design, 4e

Chapter Objectives (continued)

• Learn about standard (predefined) methods and discover how to use them in a program

• Learn about the scope of an identifier• Become aware of method overloading

Page 4: Java Programming: From Problem Analysis to Program Design, 4e

4Java Programming: From Problem Analysis to Program Design, 4e

Syntax: Method

Page 5: Java Programming: From Problem Analysis to Program Design, 4e

5

Syntax: Method

• There 3 different criteria defining types of methods:

• Modifiers: this criteria is also composed of 3 sub-criteria:» Visibility: public or private (or protected in csc 113)» Shared between all instances or not: class member (static) or

instance method.» Override able or not (final): to be discussed in CSC 113.

• Return type: method with or without (void) return value.• Parameters: with or without parameters.

• Every method have two important elements : Method head: used to declare and define the method.Method call: used to invoke and employ this method.

Page 6: Java Programming: From Problem Analysis to Program Design, 4e

6Java Programming: From Problem Analysis to Program Design, 4e

User-Defined Methods1-Method Head : • To declare a method ,the user must specify the following:• modifiers: public, private, protected, static, abstract, final

• returnType: type of the value that the method calculates and returns (using return statement)

• methodName: Java identifier; name of method • formal parameter list:The syntax of the

formal parameter list is:

Page 7: Java Programming: From Problem Analysis to Program Design, 4e

7Java Programming: From Problem Analysis to Program Design, 4e

User-Defined Methods2-Method call

-The syntax to call a value-returning method is:

- Actual parameter list are also called arguments- The syntax of the actual parameter list (arguments) is:

Page 8: Java Programming: From Problem Analysis to Program Design, 4e

8Java Programming: From Problem Analysis to Program Design, 4e

User-Defined Methods

Void Methods:• Defined by users.• Call to method is always stand-alone

statement• Can use return statement to exit method

early (optional)

Page 9: Java Programming: From Problem Analysis to Program Design, 4e

Void Methods without Parameters: SyntaxMethod Definition The definition of void method without parameters has the following syntax:

modifier(s) void methodName( ){ statements}

Method Call A method call has the following syntax:

methodName( ) ;

To call a method, you use its name.

Page 10: Java Programming: From Problem Analysis to Program Design, 4e

Void method: Example (1)

Public static void theMethod( ){ System.out.println(“3”+”+”+”4”+”=“+ (3+4));}

Page 11: Java Programming: From Problem Analysis to Program Design, 4e

Void method: Example (2)

public static void drawRectangle ( ){ System.out.println(“Enter the dimensions of your rectangle ”); int x=read.nextInt(); int y=read.nextInt(); for( int i = 0 ; i < x ; i++ ) { for( int j = 0 ; j < y ; j++ ) System.out.print(“*”); System.out.println(); }}

Page 12: Java Programming: From Problem Analysis to Program Design, 4e

12Java Programming: From Problem Analysis to Program Design, 4e

Flow of Execution – Example(void)

Public static void theMethod( ){ System.out.println(“in method “);}

Public static void main( String args[]){ System.out.println(“Before call”); theMethod(); System.out.println(“Aftere call”);}

Before callIn methodAfter call

Execution begins with the 1st

statement in main

Call to method transfers control from caller to called method

Control goes back to caller when method exits

Page 13: Java Programming: From Problem Analysis to Program Design, 4e

13Java Programming: From Problem Analysis to Program Design, 4e

Void Methods with Parameters: Syntax

Page 14: Java Programming: From Problem Analysis to Program Design, 4e

14Java Programming: From Problem Analysis to Program Design, 4e

Void Methods with Parameters: Syntax (continued)

To call a method you use its name, with the actual parameters (if any)in parentheses.

Page 15: Java Programming: From Problem Analysis to Program Design, 4e

15Java Programming: From Problem Analysis to Program Design, 4e

Formal parameters

public static void larger (double x, double y){

if ( x >= y ) System.out.print(“The max is ”+x);else System.out.print(“the max is ”+ y);

}

Formal parameters

Formal parameters list

Method nameModifiers

Methodheading

Method body

Page 16: Java Programming: From Problem Analysis to Program Design, 4e

Java Programming: From Problem Analysis to Program Design, 4e 16

Actual parameters

larger ( 2.5 , 5.4 );

larger ( num1 , num2 );

larger ( num1 , 33,2 );

Actual parametersMethod call

Actual parameters

Actual parameters

Method call

Method call

Page 17: Java Programming: From Problem Analysis to Program Design, 4e

Void method with parameters: Example

public static void drawRectangle (int x, int y ){ for( int i = 0 ; i < x ; i++ ) { for( int j = 0 ; j < y ; j++ ) System.out.print(“*”); System.out.println(); }}

Page 18: Java Programming: From Problem Analysis to Program Design, 4e

Void method with parameters: Example (print area of a

rectangle)

public static void areaofRectangle (int l, int w ){ System.out.println( “the Area of the rectangle is” + (l*w)); }

Page 19: Java Programming: From Problem Analysis to Program Design, 4e

19Java Programming: From Problem Analysis to Program Design, 4e

Flow of Execution• Execution always begins with the first statement

in the method main• User-defined methods execute only when called • Call to method transfers control from caller to

called method• In method call statement, specify only actual

parameters, not data type or method type• Control goes back to caller when method exits

Page 20: Java Programming: From Problem Analysis to Program Design, 4e

20Java Programming: From Problem Analysis to Program Design, 4e

Flow of Execution – Example(parameters)

Public static void method( String str){ System.out.println(str);}

Public static void main( String args[]){ System.out.println(“Before call”); method(“csc111”); System.out.println(“Aftere call”);}

Before callcsc111

After call

Execution begins with the 1st

statement in main

Call to method transfers control from caller to called methodand passing parameter from main to method

Control goes back to caller when method exits

Page 21: Java Programming: From Problem Analysis to Program Design, 4e

21Java Programming: From Problem Analysis to Program Design, 4e

Value returning MethodsValue-returning methods

– Used in expressions– Calculate and return a value– Can save value for later calculation or print value

Page 22: Java Programming: From Problem Analysis to Program Design, 4e

22Java Programming: From Problem Analysis to Program Design, 4e

Value returning Methods: Syntax

Page 23: Java Programming: From Problem Analysis to Program Design, 4e

Value returning Methods: Syntax

Java Programming: From Problem Analysis to Program Design, 4e 23

Page 24: Java Programming: From Problem Analysis to Program Design, 4e

24Java Programming: From Problem Analysis to Program Design, 4e

Value returning Methods: Actual and formal parameters

Page 25: Java Programming: From Problem Analysis to Program Design, 4e

25Java Programming: From Problem Analysis to Program Design, 4e

Value returning Methods: Actual and formal parameters

Page 26: Java Programming: From Problem Analysis to Program Design, 4e

26Java Programming: From Problem Analysis to Program Design, 4e

Return Statment• Syntax: return statement• return statement will return the flow of the

program from the method to the main method.• It is also used to return the value resulting from

the method to the main method to be used their. -The return statement has the following syntax:

return expr/value/variable;Important note:1-value returning methods must have a return statement2- The value they return must be the same as the method data type

Page 27: Java Programming: From Problem Analysis to Program Design, 4e

27Java Programming: From Problem Analysis to Program Design, 4e

Flow of Execution – Example(void) add return

Public static int theMethod( ){ int x= 1000; return x;}

Public static void main( String args[]){ System.out.println(“Before call”); System.out.println( theMethod()); System.out.println(“Aftere call”);}

Before call1000

After call

Execution begins with the 1st

statement in main

Call to method transfers control from caller to called method

Control goes back to caller when method exits

Page 28: Java Programming: From Problem Analysis to Program Design, 4e

28Java Programming: From Problem Analysis to Program Design, 4e

Flow of Execution – Example(parameters) add return

Public static int method(int num ){ return ++num;}

Public static void main( String args[]){ System.out.println(“Before call”); System.out.println( method(6)); System.out.println(“Aftere call”);}

Before call7

After call

Execution begins with the 1st

statement in main

Call to method transfers control from caller to called method

Control goes back to caller when method exits (return in this e.g)

Page 29: Java Programming: From Problem Analysis to Program Design, 4e

Return Statement – Equivalent Examples

public static double larger(double x, double y){ double max;

if (x >= y) max = x; else max = y;

return max;}

Java Programming: From Problem Analysis to Program Design, 4e 29

public static double larger(double x, double y)

{ if (x >= y) return x; else return y;}

public static double larger(double x, double y)

{ if (x >= y) return x; return y;}

Page 30: Java Programming: From Problem Analysis to Program Design, 4e

30Java Programming: From Problem Analysis to Program Design, 4e

The int variable num contains the number that we want to compute the factorial

Examples (1)

public static int factorial (int num )

{

int fact=1;

for (int i=2;i<=num;i++)

fact=fact*i;

return fact;

}

Page 31: Java Programming: From Problem Analysis to Program Design, 4e

31Java Programming: From Problem Analysis to Program Design, 4e

Palindrome Number• Palindrome: integer or string that reads the

same forwards and backwards• The method isPalindrome takes a string

as a parameter and returns true if the string is a palindrome, false otherwise

Examples (2)

Page 32: Java Programming: From Problem Analysis to Program Design, 4e

32Java Programming: From Problem Analysis to Program Design, 4e

public static boolean isPalindrome(String str){ int len = str.length(); int i, j; j = len - 1;

for (i = 0; i <= (len - 1) / 2; i++) { if (str.charAt(i) != str.charAt(j)) return false; j--; } return true; }

Examples (2) - Cont

Page 33: Java Programming: From Problem Analysis to Program Design, 4e

33Java Programming: From Problem Analysis to Program Design, 4e

Example (3) Largest Number

• Input: set of 10 numbers• Output: largest of 10 numbers• Solution

– Get numbers one at a time– Method largest number: returns the larger of two

numbers– For loop: calls method largest number on each number

received and compares to current largest number

Page 34: Java Programming: From Problem Analysis to Program Design, 4e

34Java Programming: From Problem Analysis to Program Design, 4e

static Scanner console = new Scanner(System.in);

public static void main(String[] args){ double num; double max; int count; System.out.println("Enter 10 numbers."); num = console.nextDouble(); max = num; for (count = 1; count < 10; count++) { num = console.nextDouble(); max = larger(max, num); } System.out.println("The largest number is " + max); }

Examples (3) - Cont

Page 35: Java Programming: From Problem Analysis to Program Design, 4e

35Java Programming: From Problem Analysis to Program Design, 4e

Sample Run: Largest Number• Sample RunEnter 10 numbers:10.5 56.34 73.3 42 22 67 88.55 26 62 11The largest number is 88.55

Examples (3) - cont

Page 36: Java Programming: From Problem Analysis to Program Design, 4e

36

Primitive VS. Reference Variables• Primitive variables hold values of primitive data

types. Example: int x = 5; x is primitive variable

• Instance variables hold references of objects: the location (memory address) of objects in memory.Example: int [] arr = {1,2,3,4,5};arr is reference variable, it carries the address of the location of the array

x 1

1100 1 2 3 4 5arr1100

Page 37: Java Programming: From Problem Analysis to Program Design, 4e

37Java Programming: From Problem Analysis to Program Design, 4e

Primitive Data Type Variables as Parameters

• A formal parameter receives a copy of its corresponding actual parameter

• If a formal parameter is a variable of a primitive data type:– Value of actual parameter is directly stored– Cannot pass information outside the method– Provides only a one-way link between actual

parameters and formal parameters

Page 38: Java Programming: From Problem Analysis to Program Design, 4e

38Java Programming: From Problem Analysis to Program Design, 4e

Reference Variables as Parameters

• If a formal parameter is a reference variable:– Copies value of corresponding actual parameter– Value of actual parameter is address of the object

where actual data is stored– Both formal and actual parameter refer to same

object

Page 39: Java Programming: From Problem Analysis to Program Design, 4e

39Java Programming: From Problem Analysis to Program Design, 4e

Uses of Reference Variables as Parameters

• Can return more than one value from a method

• Can change the value of the actual object • When passing address, would save memory

space and time, relative to copying large amount of data

Page 40: Java Programming: From Problem Analysis to Program Design, 4e

Java Programming: From Problem Analysis to Program Design, 4e 40

Declaring Arrays as Formal Parameters to Methods

• A general syntax to declare an array as a formal parameter

public static void arraysAsFormalParameter(int[] listA, double[] listB, int num){ //...}int[] intList = new int[10];double[] doubleNumList = new double[15];int number; arraysAsFormalParameter(intList, doubleNumList, number);

Page 41: Java Programming: From Problem Analysis to Program Design, 4e

Java Programming: From Problem Analysis to Program Design, 4e 41

Arrays as Parameter to Methods

Page 42: Java Programming: From Problem Analysis to Program Design, 4e

Java Programming: From Problem Analysis to Program Design, 4e 42

Methods for Array Processing

Page 43: Java Programming: From Problem Analysis to Program Design, 4e

Java Programming: From Problem Analysis to Program Design, 4e 43

Methods for Array Processing (continued)

Page 44: Java Programming: From Problem Analysis to Program Design, 4e

Java Programming: From Problem Analysis to Program Design, 4e 44

Methods for Array Processing (continued)

Page 45: Java Programming: From Problem Analysis to Program Design, 4e

Java Programming: From Problem Analysis to Program Design, 4e 45

Methods for Array Processing (elements of array as par.)

Page 46: Java Programming: From Problem Analysis to Program Design, 4e

Java Programming: From Problem Analysis to Program Design, 4e 46

public static int seqSearch(int[] list, int listLength, int searchItem){ int loc; boolean found = false; loc = 0; while (loc < listLength && !found) if (list[loc] == searchItem) found = true; else loc++; if (found) return loc; else return -1;}

Methods for Array Processing (search)

Page 47: Java Programming: From Problem Analysis to Program Design, 4e

Java Programming: From Problem Analysis to Program Design, 4e 47

Relational Operators and Arrays (example)

boolean areEqualArrays(int[] firstArray, int[] secondArray){ if (firstArray.length != secondArray.length) return false;

for (int index = 0; index < firstArray.length; index++) if (firstArray[index] != secondArray[index]) return false; return true;}

if (areEqualArrays(listA, listB))...

Page 48: Java Programming: From Problem Analysis to Program Design, 4e

Java Programming: From Problem Analysis to Program Design, 4e 48

Arrays and Variable Length Parameter List

• The syntax to declare a variable length formal parameter (list) is:dataType ... identifier

Page 49: Java Programming: From Problem Analysis to Program Design, 4e

Java Programming: From Problem Analysis to Program Design, 4e 49

Arrays and Variable Length Parameter List (continued)

Page 50: Java Programming: From Problem Analysis to Program Design, 4e

Java Programming: From Problem Analysis to Program Design, 4e 50

Arrays and Variable Length Parameter List (continued)

Page 51: Java Programming: From Problem Analysis to Program Design, 4e

Java Programming: From Problem Analysis to Program Design, 4e 51

Arrays and Variable Length Parameter List (continued)

• A method can have both a variable length formal parameter and other formal parameters; consider the following method heading: public static void myMethod(String name,

double num, int ... intList)• The formal parameter name is of type String, the

formal parameter num is of type double, and the formal parameter intList is of variable length

• The actual parameter corresponding to intList can be an int array or any number of int variables and/or int values

Page 52: Java Programming: From Problem Analysis to Program Design, 4e

Java Programming: From Problem Analysis to Program Design, 4e 52

Arrays and Variable Length Parameter List (continued)

• A method can have at most one variable length formal parameter

• If a method has both a variable length formal parameter and other types of formal parameters, then the variable length formal parameter must be the last formal parameter of the formal parameter list

Page 53: Java Programming: From Problem Analysis to Program Design, 4e

53Java Programming: From Problem Analysis to Program Design, 4e

Reference Variables as Parameters: type String (special case)

Page 54: Java Programming: From Problem Analysis to Program Design, 4e

54Java Programming: From Problem Analysis to Program Design, 4e

Reference Variables as Parameters: type String (continued)

Page 55: Java Programming: From Problem Analysis to Program Design, 4e

55Java Programming: From Problem Analysis to Program Design, 4e

Reference Variables as Parameters: type String (continued)

Page 56: Java Programming: From Problem Analysis to Program Design, 4e

56Java Programming: From Problem Analysis to Program Design, 4e

Reference Variables as Parameters: type String (continued)

Page 57: Java Programming: From Problem Analysis to Program Design, 4e

57Java Programming: From Problem Analysis to Program Design, 4e

Reference Variables as Parameters: type String (continued)

String str = "Hello"; //Line 5

Page 58: Java Programming: From Problem Analysis to Program Design, 4e

58Java Programming: From Problem Analysis to Program Design, 4e

Reference Variables as Parameters: type String (continued)

stringParameter(str); //Line 7

Page 59: Java Programming: From Problem Analysis to Program Design, 4e

59Java Programming: From Problem Analysis to Program Design, 4e

Reference Variables as Parameters: type String (continued)

pStr = "Sunny Day"; //Line 14

Page 60: Java Programming: From Problem Analysis to Program Design, 4e

60Java Programming: From Problem Analysis to Program Design, 4e

Reference Variables as Parameters: type String (continued)

Variables before the statement in Line 8 executes

Page 61: Java Programming: From Problem Analysis to Program Design, 4e

61Java Programming: From Problem Analysis to Program Design, 4e

Predefined Classes

• Methods already written and provided by Java

• Organized as a collection of classes (class libraries)

• To use: import package • Method type: data type of value returned by

method

Page 62: Java Programming: From Problem Analysis to Program Design, 4e

62Java Programming: From Problem Analysis to Program Design, 4e

Predefined Classes (continued)

Page 63: Java Programming: From Problem Analysis to Program Design, 4e

63Java Programming: From Problem Analysis to Program Design, 4e

Predefined Classes (continued)

random() return a value of type double greater than or equal to 0.0 and less than 1.0.

Page 64: Java Programming: From Problem Analysis to Program Design, 4e

64Java Programming: From Problem Analysis to Program Design, 4e

Predefined Classes (continued)

Page 65: Java Programming: From Problem Analysis to Program Design, 4e

Exampledouble x = Math.pow(3,2); double area = Math.PI*radius*radius;

- If you use the static import statement, you can omit the name of class

import static java.lang.Math.*;double x = pow(3,2);

Java Programming: From Problem Analysis to Program Design, 4e 65

Page 66: Java Programming: From Problem Analysis to Program Design, 4e

Generating random variable in range

• General form range = (max - min) + 1; [min,max] OR range = (max - min) ; [min,max[ randomNum = (int) (Math.random()* range)+minimum ;

• Rollin dice int dice2 = (int) (Math.random() * 6) + 1;

Java Programming: From Problem Analysis to Program Design, 4e 66

Page 67: Java Programming: From Problem Analysis to Program Design, 4e

67Java Programming: From Problem Analysis to Program Design, 4e

class Character (Package: java.lang)

Page 68: Java Programming: From Problem Analysis to Program Design, 4e

68Java Programming: From Problem Analysis to Program Design, 4e

class Character (Package: java.lang) (continued)

Page 69: Java Programming: From Problem Analysis to Program Design, 4e

69Java Programming: From Problem Analysis to Program Design, 4e

class Character (Package: java.lang) (continued)

Page 70: Java Programming: From Problem Analysis to Program Design, 4e

70Java Programming: From Problem Analysis to Program Design, 4e

Scope of an Identifier within a Class

• Local identifier: identifier declared within a method or block, which is visible only within that method or block

• Java does not allow the nesting of methods; you cannot include the definition of one method in the body of another method

• Within a method or a block, an identifier must be declared before it can be used; a block is a set of statements enclosed within braces

Page 71: Java Programming: From Problem Analysis to Program Design, 4e

Scope of an Identifier within a Class (continued)

• A method’s definition can contain several blocks – The body of a loop or an if statement also

form a block• Within a class, outside of every method

definition (and every block), an identifier can be declared anywhere

Java Programming: From Problem Analysis to Program Design, 4e 71

Page 72: Java Programming: From Problem Analysis to Program Design, 4e

Scope of an Identifier within a Class (continued)

• Within a method, an identifier used to name a variable in the outer block of the method cannot be used to name any other variable in an inner block of the method

• For example, in the method definition on the next slide, the second declaration of the variable x is illegal

Java Programming: From Problem Analysis to Program Design, 4e 72

Page 73: Java Programming: From Problem Analysis to Program Design, 4e

73Java Programming: From Problem Analysis to Program Design, 4e

Scope of an Identifier within a Class (continued)

public static void illegalIdentifierDeclaration(){ int x; //block { double x; //illegal declaration, //x is already declared ... }}

Page 74: Java Programming: From Problem Analysis to Program Design, 4e

74Java Programming: From Problem Analysis to Program Design, 4e

Scope Rules• Scope rules of an identifier declared within a class and accessed within a method (block) of the class

• An identifier, say X, declared within a method (block) is accessible:– Only within the block from the point at which it is

declared until the end of the block– By those blocks that are nested within that block

Page 75: Java Programming: From Problem Analysis to Program Design, 4e

75Java Programming: From Problem Analysis to Program Design, 4e

public static int w; public static void two(int one, int z) { char ch; int a; //block three { int x = 12; //... } //end block three //... }}

Scope Rules (continued) Example 7-11

Page 76: Java Programming: From Problem Analysis to Program Design, 4e

Scope Rules (continued)

• Suppose X is an identifier declared within a class and outside of every method’s definition (block) – If X is declared without the reserved word static (such

as a named constant or a method name), then it cannot be accessed in a static method

– If X is declared with the reserved word static (such as a named constant or a method name), then it can be accessed within a method (block), provided the method (block) does not have any other identifier named X

Java Programming: From Problem Analysis to Program Design, 4e 76

Page 77: Java Programming: From Problem Analysis to Program Design, 4e

77Java Programming: From Problem Analysis to Program Design, 4e

public class ScopeRules{ static final double rate = 10.50; static int z; static double t; public static void main(String[] args) { int num; double x, z; char ch; //... } public static void one(int x, char y) { //... }

Scope Rules (continued) Example 7-11

Page 78: Java Programming: From Problem Analysis to Program Design, 4e

78Java Programming: From Problem Analysis to Program Design, 4e

public class ScopeRules{ static final double rate = 10.50; static int z; static double t; public static void main(String[] args) { int num; double x, z; char ch; //... } public static void one(int x, char y) { //... } public static int w; public static void two(int one, int z) { char ch; int a; { int x = 12;

} //... }}

Scope Rules (continued) Example 7-11

static final double rate static int z;static double t;mainint num;double x, z;char ch;

Method oneone(int x, char y)public static int w;

Method twotwo(int one, int z)char ch; int a;

int x = 12;

Page 79: Java Programming: From Problem Analysis to Program Design, 4e

79Java Programming: From Problem Analysis to Program Design, 4e

Scope Rules: Demonstrated (continued)

Page 80: Java Programming: From Problem Analysis to Program Design, 4e

80Java Programming: From Problem Analysis to Program Design, 4e

Scope Rules: Demonstrated

Page 81: Java Programming: From Problem Analysis to Program Design, 4e

Scope Rules – Scanner Examplepublic class ScopeRules { static Scanner read=new Scanner (System.in); public static void main(String[] args){ int number = read.nextInt(); //… } }

Java Programming: From Problem Analysis to Program Design, 4e 81

public class ScopeRules { public static void main(String[] args){ Scanner read=new Scanner (System.in); int number = read.nextInt(); //… } }

Can be accessed from any method

(static & non-static) including main,

‘Local ‘ accessed from main only

public class ScopeRules { Scanner read=new Scanner (System.in); public static void main(String[] args){ int number = read.nextInt(); //… } }

Can be accessed from non-static

method only

Page 82: Java Programming: From Problem Analysis to Program Design, 4e

82Java Programming: From Problem Analysis to Program Design, 4e

Method Overloading: An Introduction

• Method overloading: more than one method can have the same name

• Two methods are said to have different formal parameter lists if both methods have:– A different number of formal parameters, or– If the number of formal parameters is the same,

then the data type of the formal parameters, in the order you list, must differ in at least one position

Page 83: Java Programming: From Problem Analysis to Program Design, 4e

83Java Programming: From Problem Analysis to Program Design, 4e

Method Overloading

public void methodOne(int x)public void methodTwo(int x, double y)public void methodThree(double y, int x)public int methodFour(char ch, int x, double y)public int methodFive(char ch, int x, String name)

• These methods all have different formal parameter lists

Page 84: Java Programming: From Problem Analysis to Program Design, 4e

84Java Programming: From Problem Analysis to Program Design, 4e

Method Overloading (continued)

public void methodSix(int x, double y, char ch)public void methodSeven(int one, double u, char firstCh)

• The methods methodSix and methodSeven both have three formal parameters and the data type of the corresponding parameters is the same

• These methods all have the same formal parameter lists

Page 85: Java Programming: From Problem Analysis to Program Design, 4e

85Java Programming: From Problem Analysis to Program Design, 4e

Method Overloading (continued)

• Method overloading: creating several methods, within a class, with the same name

• The signature of a method consists of the method name and its formal parameter list

• Two methods have different signatures if they have either different names or different formal parameter lists– Note that the signature of a method does not include

the return type of the method

Page 86: Java Programming: From Problem Analysis to Program Design, 4e

86Java Programming: From Problem Analysis to Program Design, 4e

Method Overloading (continued)

• The following method headings correctly overload the method methodXYZ:

public void methodXYZ()public void methodXYZ(int x, double y)public void methodXYZ(double one, int y)public void methodXYZ(int x, double y, char ch)

Page 87: Java Programming: From Problem Analysis to Program Design, 4e

87Java Programming: From Problem Analysis to Program Design, 4e

Method Overloading (continued) public void methodABC(int x, double y) public int methodABC(int x, double y)

• Both these method headings have the same name and same formal parameter list

• These method headings to overload the method methodABC are incorrect

• In this case, the compiler will generate a syntax error– Notice that the return types of these method headings are different

Page 88: Java Programming: From Problem Analysis to Program Design, 4e

88Java Programming: From Problem Analysis to Program Design, 4e

Chapter Summary

• Predefined methods• User-defined methods

– Value-returning methods– Void methods– Formal parameters– Actual parameters

• Flow of Execution

Page 89: Java Programming: From Problem Analysis to Program Design, 4e

89Java Programming: From Problem Analysis to Program Design, 4e

Chapter Summary (continued)

• Primitive data type variables as parameters– One-way link between actual parameters and

formal parameters (limitations caused)• Reference variables as parameters

– Can pass one or more variables from a method– Can change value of actual parameter

• Scope of an identifier within a class• Method overloading