Methods Additional Topics Copyright © 1997 - 2009 Curt Hill
Topics Returning values Name overloading Copyright © 1997 - 2009 Curt Hill
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 © 1997 - 2009 Curt Hill
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 © 1997 - 2009 Curt Hill
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 © 1997 - 2009 Curt Hill
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 © 1997 - 2009 Curt Hill
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 © 1997 - 2009 Curt Hill
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 © 1997 - 2009 Curt Hill
Example Consider: int square(int a){ return a*a; } float square(float a){ return a*a; } Copyright © 1997 - 2009 Curt Hill
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 © 1997 - 2009 Curt Hill
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 © 1997 - 2009 Curt Hill
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 © 1997 - 2009 Curt Hill