一、方法重载:
方法重载规则
1.方法返回值不做要求
2.方法名必须相同
3.形参列表不同,不同指的是形参类型不同或者形参个数不同
4.方法名和形参列表必须同时满足要求
在这里插入代码片
/**方法重载
*/
public class Method{
public static void main(String[] args){
int x = 1;
int y = 6;
int z = 57;
System.out.println(method(x,y));
System.out.println(method(x,y,z));
/**
如果要调用返回值为double的这个方法,则需要给double类型的形参,比如 System.out.println(method(2.1,3.2,4.2)); 这样就可以调用*/
}
public static int method(int a,int b){
return a+b;
}
public static int method(int a,int b,int c){
return a+b+c;
}
public static double method(double a,double b,double c){
return a+b+c;
}
}
总结:重载规则针对于在同一个类中的方法
二、方法递归:
1.要调用自身
2.有一个趋近于终止的条件
3.推导出递推公式
1.求N的阶乘的例子
//求N的阶乘
public static int fac(int n) {
if(n == 1){
return 1;
}
int count = n*fac(n-1);
return count;
}
//
2.求1~n的和
public static int sumInt(int x){
if(x == 1){
return 1;
}
int count = x+sumInt(x-1);
return count;
}
3.按顺序输出一个整数
public static void inPut(int n) {
if(n>9){
inPut(n/10);
}
System.out.println(n%10);
}
4.输出斐波那契数列
public static void feiBoNa(int x){
int i1 = 1;
int i2 = 1;
int i3 = 0;
System.out.print(1 +" " +1 + " ");
for(int i = 3;i <= x;i++){
i3 = i1 +i2;
i2 = i1;
i1 = i3;
System.out.print(i3 + " ");
}
}
总结:
递归是一种重要的变成解决问题的方式,有一些问题就是用递归定义的,如斐波那契数列用递归就很容易解决。有些问题用循环或者递归都能解决,那么则推荐使用循环解决,相比于递归,循环更高效。