(1)格式:
方法名定义规则参照变量定义规则,使用小驼峰命名 helloWorld
注意定义的位置:
类里面,方法外面
方法定义后需要被调用,才能被执行
(2)调用方法
方法名();
方法执行先后顺序与调用顺序有关
(3)带参方法
格式:
public static void 方法名(){
//代码
}
修饰符 返回值类型 方法名称(参数类型 参数1名称,参数类型 参数2名称){
//方法体
//return 返回值;
}
调用方法:
1、直接调用:方法名称(参数1,参数2);
2、打印调用:System.out.println(方法名称(参数1,参数2));
3、赋值调用:数据类型 变量名称 = 方法名(参数);
(4)数组方法
调用方式和普通方法一样
数组做返回值
public static int[] Shuzufangfa(){
int[] arr=new int[]{1,2,3};
return arr;
}
数组做参数
public static void Shuzufangfa2(int[] arr){
}
数组做参数和返回值
public static int[] Shuzufangfa3(int[] arr){
arr=new int[]{1,2,3};
return arr;
}
(5)重载方法
就是在类中可以创建多个方法,它们可以有相同的名字,但必须具有不同的参数,即或者是参数的个数不同,或者是参数的类型不同。
调用
方法名(对应参数类型);
public static void f1() {}
public static int f1(double a) { return 5;}
public static void f1(int a, int b) { }
public static void f1(int b) { }
public static void f1(int a, double b, int c) { }
public static void f1(double b, int a, int c) { }
public static void f1(int c, int a, double b) { }
//public static void F1(){} 不是重载方法,方法名不同
//public static void f1(int c){} 不是重载方法
//public static void f1(int b,int a){} 不是跟类型有关