1.方法的重载
含义:方法与方法之间的关系
条件:
1.在同一个类中
2.方法名一致
3.参数列表的个数或类型不一致
4.与返回值无关(方法是否有返回值、返回什么值跟方法的重载关系是无关的)
好处:系统会根据实参类型自动匹配到对应的方法里
需求1:设计一个方法,传入两个int值,返回最大值
需求2:设计一个方法,传入三个int值,返回最大值
需求3:设计一个方法,传入两个double值,返回最大值
需求4:设计一个方法,传入三个double值,返回最大值public static void main(String[] args){ //打印getMax的方法,这个方法必须有返回值才能打印,否则会报错 System.out.println(getMax(10.1,20)); } public static int getMax(int a,int b){ int max = (a>b)?a:b; return max; } public static int getMax(int a,int b,int c){ int max = getMax(a,b); max = getMax(a,b);//改进后调用方法的代码 return max; } public static double getMax(double a,double b){ double max = (a>b)?a:b; return max; } public static double getMax(double a,double b,double c){ double max = getMax(a,b); max = getMax(a,b); return max; } }
2.方法的递归
1.含义:方法调用方法自身
2.经验:找规律、找出口
1).找规律:知道方法何时调用方法自身 2).找出口:知道方法何时结束
需求:设计一个方法,传入int类的值n,求n的阶乘
分析:
5! -> 1*2*3*4*5 -> 4!*5
4! -> 1*2*3*4 -> 3!*4
3! -> 1*2*3 -> 2!*3
2! -> 1*2 -> 1!*2
1! -> 1 -> 1
找规律:n! = (n-1)! * n;
找出口:1! = 1;public static void main(String[] args){ int num = getFactorial(5); System.out.println(num); } public static int getFactorial(int n){ if(n != 1){ return getFactorial(n-1) * n; }else{ return 1; } }