一、简介
Java方法时语句的集合,它们在一起执行一个功能,设计方法时,最好保持方法的原子性,即一个方法只完成一个功能,这样有利于后期的扩展。
二、方法创建
三、有参方法与无参方法
3.1、有参方法
3.2、无参方法
四、方法的重载
4.1、定义:
在同一个类中,方法名相同,参数不同(参数的类型,数量,顺序);
4.2、参数类型不同
package com.massimo.charpter7;
public class Test07 {
public static void main(String[] args) {
int result = add(1, 3);
System.out.println(result);
System.out.println("=====================");
double result2 = add(1.0, 3.0);
System.out.println(result2);
}
public static int add(int a , int b){
System.out.println("方法1");
return a + b;
}
public static double add(double a , double b){
System.out.println("方法2");
return a + b;
}
}
4.3、参数数量不同
package com.massimo.charpter7;
public class Test07 {
public static void main(String[] args) {
double result = add(1, 3);
System.out.println(result);
System.out.println("=======================");
double result2 = add(1, 3, 2);
System.out.println(result2);
}
public static double add(int a , int b){
System.out.println("方法1");
return a + b;
}
public static double add(int a , int b , int c){
System.out.println("方法1");
return a + b + c ;
}
}
4.4、参数的顺序不同
package com.massimo.charpter7;
public class Test07 {
public static void main(String[] args) {
double result = add(1, 3.0);
System.out.println(result);
System.out.println("=======================");
double result2 = add(1.0, 4);
System.out.println(result2);
}
public static double add(int a , double b){
System.out.println("方法1");
return a + b;
}
public static double add(double a , int b){
System.out.println("方法1");
return a + b ;
}
}
五、递归
方法自己调用自己。
两个部分:
递归头:什么时候不调用自身方法。如果没有头,将陷入死循环。
递归体:什么时候需要调用自身方法。
package com.massimo.charpter7;
public class Test07 {
public static void main(String[] args) {
double result = recursive(5);
System.out.println(result);
}
public static double recursive(double a){
if(a == 1){
return 1; //递归头:当a等于1时,返回1,结束递归
}
return a * recursive(a-1); //递归体
}
}