方法名相同,返回值可以不同,参数个数或参数类型必须不同。
重载
java语法:
public class Sort { public static int Sum(int a ,int b){ return a+b; } public static double Sum(double a ,int b){ return a+b; } public static int Sum(int a ,int b,int c){ return a+b+c; } public static double Sum(int a ,int b,double c){ return a+b+c; } public static void main(String[] args) { System.out.println(Sum(3,5)); System.out.println(Sum(3.0,5)); System.out.println(Sum(3,5,4)); System.out.println(Sum(3,5,4.0)); } }
递归:求N的阶乘相加
Java语法
public class Sort {
public static int Factorial(int a){ if (a==1){ return 1; } return a*Factorial(a-1); } public static int Factorial1(int a){ if (a==1){ return Factorial(a); } return Factorial(a)+Factorial1(a-1); }
public static void main(String[] args) { System.out.println(Factorial1(5)); } }