提高代码的复用性,完成特定功能的代码块。
格式
修饰符 返回值类型 方法名(参数类型 参数名1,参数类型 参数名2...) {
方法体语句;
return 返回值;
}
修饰符:publc、protected、private...
返回值类型:返回值的数据类型
方法名:符合命名规范的名字
():参数
参数类型:参数的数据类型
参数名:形参
方法体语句:方法要实现的功能代码
return:结束方法
返回值:功能代码实现的结果,由return带给调用者
public static void log(){
System.out.println("不能用单引号很不习惯");
}
log();//输出 不能用单引号很不习惯
public static void sum(int a , int b){
int c = a + b;
return c;
}
System.out.println(sum(1,2));//3
public static void str(int a){
if(a > 10){
System.out.println(a + "> 10“);
return;
}
System.out.orintln(a + "< 10");
}
str(2);//a<10
str(20);//a>10
方法重载
在同一个类中,方法名相同,参数列表不同。与返回值类型无关。
参数个数不同
参数类型不同
double sum1 = add(10,20.1);
System.out.println(sum1);
int sum2 = add(10,20,30);
System.out.println(sum2);
double sum3 = add(12.3,13);
System.out.println(sum3);
public static double add(int a,double b) {
return a + b;
}
public static int add(int a,int b,int c) {
return a + b + c;
}
public static double add(double a,int b) {
return a + b;
}