custom function
Key Points:
- Functions must be placed in a class
- Modifiers public, static, return value, int, void, char... function name (formal parameter list) {function body}
- Usually, methods are public modified, public, easy to call
- Functions can call functions, classes such as main function call...
- For recursive functions, pay attention to the termination condition
Custom function instance for recursive factorial
public class Demo07 {
public static void main(String[] args) {
int a = 5;
System.out.println(a(a));
}
//自定义函数,函数调用自己,只不过对参数进行了-1操作
public static int a(int a){
if(a>1){
return a*a(a-1);
}else{
return 1;
}
}
}
function overloading
In a class, the function name is the same, that is, overloading. It should be noted that the parameters of the overloaded function 个数
or 类型
must be different.
The function name is the same, the parameters are the same, the return value is different, and this is wrong, it is forbidden
public class Demo02 {
public static void main(String[] args) {
System.out.println(max(2.6,4.8,3.6));
}
public static int max(int a,int b){
int c = a>b?a:b;
return c;
}
public static double max(double a,double b){
double c = a>b?a:b;
return c;
}
public static double max(double a,double b,double c){
if(a>b){
return a;
}else if(b>c){
return b;
}else{
return c;
}
}
}