function
(1) Definition of functions
A function is an independent small program defined in a class with a specific function
function also known as method
Format of the function
modifier return value type function name (parameter type formal parameter 1, formal parameter 2....) {
execute statement;
return return value;
}
Return value type: The data type of the result after the function runs
parameter type: is the data type of the formal parameter
Formal parameter: is a variable that stores the actual parameters passed to the function when the function is called
Actual parameter: the specific value passed to the formal parameter
return, used to end the function
Return value: The result of the function operation, the result will be returned to the caller
(2) Features of the function
Defining functions can encapsulate functional code
It is easy to reuse this function
The function will only be executed if it is called
The emergence of functions improves the reusability of the code
For the case that the function does not have a return value, the return value type is represented by the keyword void, then the return statement in the function can be omitted if it is in the last line.
Note:
A function can only call a function, you cannot define a function inside a function
When defining a function, the result of the function should be returned to the caller for processing by the caller
(3) Application of functions
example:
Define a function that can implement the sum of two numbers, which is also an integer (int)
int getSum(int x,int y){
return x+y;
}
(4) Function overloading (overload)
In the same class, more than one function with the same name is allowed, as long as they have different parameter numbers or parameter types
The characteristics of overloading: have nothing to do with the return value type, just look at the parameter list
The benefits of overloading: easy to read, optimized program design
example:
int add (int x, int y) {
return x+y;
}
int add (int x, int y, int z) {
return x+y+z;
}
double add(double x,double y){
return x+y;
}