方法調用
Java支持兩種調用方法的方式,根據方法是否返回值來選擇。
當程序調用一個方法時,程序的控制權交給了被調用的方法。當被調用方法的返回語句執行或者到達方法體閉括號時候交還控制權給程序。
當方法返回一個值的時候,方法調用通常被當做一個值。例如:
1
|
int larger = max( 30 , 40 ); |
如果方法返回值是void,方法調用一定是一條語句。例如,方法println返回void。下面的調用是個語句:
1
|
System.out.println( "Welcome to Java!" ); |
示例
下面的例子演示了如何定義一個方法,以及如何調用它:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public class TestMax { /** 主方法 */ public static void main(String[] args) { int i = 5 ; int j = 2 ; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); } /** 返回兩個整數變量較大的值 */ public static int max( int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } } |
以上實例編譯運行結果如下:
1
|
The maximum between 5 and 2 is 5 |
這個程序包含main方法和max方法。Main方法是被JVM調用的,除此之外,main方法和其它方法沒什么區別。
main方法的頭部是不變的,如例子所示,帶修飾符public和static,返回void類型值,方法名字是main,此外帶個一個String[]類型參數。String[]表明參數是字符串數組。
調用實例:
一、調用本類中的方法
方法一、被調用方法聲明為static ,可以在其他方法中直接調用。示例代碼如下:
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
26
27
28
29
30
31
32
33
34
35
|
public class HelloWord { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String str= "HelloWord!" ; int a= 0 ; int b=a+ 1 ; int result= 0 ; for ( int i= 0 ;i< 20 ;i++) { //Add方法調用 result= Add(a,b); System.out.println(str+ " " + result); a+=i; } } /** * 被調用方法,這里使用了static聲明為靜態方法 * @param x * @param y * @return */ private static int Add( int x, int y) { return x+y; } } |
方法二、被調用方法,沒被static修飾,不是靜態方法。調用時需要通過類的實例化進行調用。示例如下:
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
public class HelloWord { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String str= "HelloWord!" ; int a= 0 ; int b=a+ 1 ; int result= 0 ; for ( int i= 0 ;i< 20 ;i++) { //Add方法調用 //類的實例化 HelloWord helloword= new HelloWord(); //通過實例化的類進行Add方法調用 result=helloword.Add(a, b); System.out.println(str+ " " + result); a+=i; } } /** * 被調用方法,沒被static修飾,不是靜態方法。調用時需要通過類的實例化進行調用 * @param x * @param y * @return */ private int Add( int x, int y) { return x+y; } } |
二、調用外部的類的方法,通過類的實例化進行調用。示例代碼如下:
外部的類:
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 Test { /** * 被調用方法Add * @param x * @param y * @return */ public int Add( int x, int y) { return x+y; } /** * 被調用方法Sub * @param x * @param y * @return */ public static int Sub( int x, int y) { return x-y; } } |
調用:
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
26
27
28
29
30
31
32
33
|
public class HelloWord { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String str= "HelloWord!" ; int a= 5 ; int b=a+ 1 ; int result= 0 ; for ( int i= 0 ;i< 20 ;i++) { //Add方法調用 //類的實例化 Test test= new Test(); //通過實例化的類進行Add方法調用 result=test.Add(a, b); System.out.println(str+ " " + result); result=test.Sub(b, 1 ); System.out.println(str+ " " + result); a+=i; } } } |