方法
方法定义
以public static开头
public static 类型 方法名()
{
}
1 2 3 4 5 6 7 8 9 10
| public class test010 { public static void main(String[] args) { System.out.println(""); } public static void funName(int a) { } }
|
方法的三种调用格式
单独调用
方法名([参数])
1 2 3 4 5 6 7 8 9 10
| public class test010 { public static void main(String[] args) { funName(20); System.out.println(""); } public static void funName(int a) { } }
|
打印调用
System.out.println(方法名([参数]))
1 2 3 4 5 6 7 8 9 10
| public class test010 { public static void main(String[] args) { System.out.println( funName(20) ); } public static int funName(int a) { return a + 10; } }
|
赋值调用
int a = 方法名([参数])
1 2 3 4 5 6 7 8 9 10
| public class test010 { public static void main(String[] args) { int a = funName(20); } public static int funName(int a) { return a + 10; } }
|
方法分为两种
参数
有参数
无参数
1 2 3 4 5 6 7 8 9 10 11 12 13
| public class test010 { public static void main(String[] args) { } public static int funName(int a) { return a + 10; } public static int funName() { return 10; } }
|
返回值
有返回值
无返回值
1 2 3 4 5 6 7 8 9 10 11 12 13
| public class test010 { public static void main(String[] args) { } public static int funName(int a) { return a + 10; } public static void funName() { return ; } }
|
方法注意事项
方法应该定义类中,不能定义在方法中
方法定义没有前后顺序
方法定义之后不会自动执行,需要手动调用
如果方法有返回值,必须写上 return 返回值
返回的数据必须要和返回值类型一致
对于void返回值类型,可以只写return;
一个方法可以有多个return,但只能执行其中一个
方法重载Overload
如果功能相同,参数不同,可以使用方法重载
特征
方法名要相同
参数个数不同
参数类型不同
类型名 参数顺序不同
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| public class test010 { public static void main(String[] args) { } public static int funName(int a) { return a + 10; } public static int funName() { return 10; } public static int funName(int a,int b) { return a + b; } public static int funName(double a,int b) { return (int)a + b; } public static int funName(int a,double b) { return a + (int)b; } }
|