自定义函数

要点:
- 函数必须放在类中
- 修饰词public,static,返回值,int,void,char……函数名(形参列表){函数体}
- 通常,对于方法都是public修饰的,公开,方便调用
- 函数可以调用函数,类如main函数调用……
- 对于递归函数,注意终止条件
递归阶乘的自定义函数实例
public class Demo07 {
public static void main(String[] args) {
int a = 5;
System.out.println(a(a));
}
public static int a(int a){
if(a>1){
return a*a(a-1);
}else{
return 1;
}
}
}

函数重载
在一个类中,函数名一样,即重载,要注意,重载函数参数的个数 或者类型 必须有所不同
函数名相同参数相同返回值不同这样的是错误的,禁止
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;
}
}
}

|