Presentation is loading. Please wait.

Presentation is loading. Please wait.

Methods Additional Topics

Similar presentations


Presentation on theme: "Methods Additional Topics"— Presentation transcript:

1 Methods Additional Topics
Copyright © Curt Hill

2 Topics Returning values Name overloading
Copyright © Curt Hill

3 The Return Type The first required part of the method header
May be any type – void, primitive or object Consider examples: public static void main(…){…} static double fixer(int i){…} private char myFunction(…){…} String massage(String y){…} Copyright © Curt Hill

4 Notes The visibility is optional
public, private and protected are possible visibilities The keyword static may be included or not Depends on needs of the method The return type is required for all methods Other than constructors, which must return the object constructed They also must have the same name as the class Copyright © Curt Hill

5 The return statement Has two effects
Ends the function and returns to calling statement Determines the value that needs to be returned Form is: return expression; Expression should match return type A void method needs no return Copyright © Curt Hill

6 Call return sequence Consider this very simple sequence: static int four(){ return 4; } … public static void main(…) { System.out.println(four()); The method is called The 4 is identified as the return value This is displayed in the message Copyright © Curt Hill

7 Name Overloading In many languages such as C, Pascal, VB a function is defined by one thing only: the function name C++ introduced function name overloading It determines the function to use by examining the signature Java does the same Copyright © Curt Hill

8 Method Signatures A method is uniquely determined by two things: the name the parameter list The contribution of the parameter list does not include the parameter names, only number, type and order These are collectively called the signature Two signatures within a class may not be the same Copyright © Curt Hill

9 Example Consider: int square(int a){ return a*a; } float square(float a){ return a*a; } Copyright © Curt Hill

10 Notes There is no conflict between the two
The compiler can tell which is intended Consider: int i, j; float f,g; … int j = square(i); double g = square(f); The result type does not distinguish Only name and parameter types Copyright © Curt Hill

11 Why? Function name overloading means that we can use the right name for a method Even if the name has already been used Both square methods did the same thing Just on different types of parameters Since types are so important we do not have to have a different name for the integer version as the double version Copyright © Curt Hill

12 Finally Most of this has been a review of previous material
It needs to extra emphasis Methods are the building blocks of programs Each of which is a class Copyright © Curt Hill


Download ppt "Methods Additional Topics"

Similar presentations


Ads by Google