自定义函数

  • <mark>函数必须放在类的范围里面</mark>
  • 修饰词(public 或者static) 返回值(int或者void) 函数名(形参列表){
    函数体
    }
  • 通常情况下,我们都建议方法是public
  • 函数可以调用其他的函数,例如下面的例子,main函数调用了add函数
public class FunctionTest {
	public static void main(String[] args) {
		int a, b, c;
		a = 1;
		b = 2;
		c = FunctionTest.add(a, b);//调用函数
		System.out.println("c is " + c);
	}
	public static int add(int m, int n) // 函数定义
	{
		return m + n;
	}
}

  • 递归函数调用,<mark>需要注意终止性</mark>
public class FactorialTest {
	public static void main(String[] args) {
		int a = 5;
		int b = factorialCalculation(a);
		System.out.println("The factorial of " + a + " is " + b);
	}
	public static int factorialCalculation(int m) {
		if (m > 1) {
			return m * factorialCalculation(m - 1);
		} else {
			return 1;
		}
	}
}
  • 同一个类中,函数名称可以相同,即重载函数(overload),但是<mark>函数参数的个数或者类型必须有所不同</mark>
  • <mark>不能以返回值区分同名的函数</mark>

public class OverloadTest {

	public static void main(String[] args) {
		int a=1,b=2;
		System.out.println(add(1,2));
		System.out.println(add(1.5,2.5));
	}

	public static int add(int m, int n) 
	{
		return m + n;
	}
	public static double add(double m, double n) //和第9行行数重载overload
	{
		return m + n;
	}
	/* * 以下函数非法,和第9行的函数名相同,形参相同 public static double add(int m, int n) { return (double) (m + n); } */
}

总结:

  • 函数可以相互调用
  • <mark>函数重载条件:函数名,形参类型,个数其中一个至少不同</mark>