方法
就是语句的集合,是一个有序排列的组合,执行一个功能。
包含在类或者对象中,在程序中船舰后在其他地方调用。
一个方法只完成一个功能(原子性)。
类似于其他语言的函数,用来完成特定功能的代码片段。
- 方法定义:
– 修饰符:
public > protected > default > private
– 返回值类型:
void 无返回值
– 方法名:
main()
– 参数类型:
形式参数 — 定义作用 add(int a, int b );
实际参数 — 实际调用传递给它的数 int sum = add (1,2);
– 方法体:
具体语句,定义方法功能
– return:
返回值 或 终止方法
例: public static void main(String[] args) {
int sum = add(1,2);
System.out.println(sum);
}
public static int add(int a,int b){
return a+b;
}
- 方法调用:
支持两种调用方式,根据方法是否返回值选择
int larger = max(30,40) ; 返回值
System.out.println(“hello”); 返回语句
public static void main(String[] args) {
int max = max(10,20);
System.out.println(max);
}
public static int max(int num1,int num2){
int result = 0;
if(num1 == num2){
System.out.println("num1 == num2");
return 0; //终止方法
}
if(num1 > num2){
result = num1;
}else{
result = num2;
}
return result;
}
- 方法重载:
一个类中,方法名相同,参数不同的两个方法
public static void main(String[] args) {
add(10,20); //自动匹配和方法类型相同的方法
}
public static int add(int a,int b) {
int sum = a + b;
}
public static double add(double a,double b) {
double sum = a + b;
}
- 可变(不定向)参数
在方法声明中,在指定参数类型后加一个省略号(…)
一个方法只能指定一个可变参数,它必须是方法的最后一个参数,任何普通的参数必须在它之前声明。
public static void main(String[] args) {
Demo4 demo4 = new Demo4();
demo4.test(1,2,3,4,5,6);
}
public void test(int ... i){ //可变参数定义
System.out.println(i[0]); //取数组中第一个
}
结果: 1
- 递归 A调用A
递归头 – 什么时候调用自身方法。没有头将陷入死循环。
递归尾 – 什么时候需要调用自身方法。
举例 StackOverflowError:
public static void main(String[] args) {
Demo5 dd = new Demo5();
dd.test();
}
public void test(){
test();
}