方法

茴香豆 Lv5

方法是语句的集合,他们一起执行一个功能

方法的定义与调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.hui.t3;

import java.sql.SQLOutput;

public class Demo01 {
// main方法
public static void main(String[] args) {
int sum = add(1, 2); // Java 是值传递,不是引用传递
System.out.println(sum);
}
// 加法
public static int add(int a, int b){
return a + b;
}
}

方法的重载

一个类中,有相同的方法名称,但是类型不同。

方法的重载规则:

  • 方法名称必须相同
  • 参数列表必须不同
  • 方法返回类型可以相同也可以不同
  • 仅仅返回类型不同不足以称为方法的重载
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.hui.t3;

import java.sql.SQLOutput;

public class Demo01 {
// main方法
public static void main(String[] args) {
double sum = add(1, 2); // Java 是值传递,不是引用传递
System.out.println(sum);
}
// 加法 程序通过参数个数、参数类型等来匹配应当使用哪个方法
public static double add(double a, double b){
return a + b;
}
public static int add(int a, int b){
return a + b;
}
public static int add(int a, int b, int c){
return a + b + c;
}
}

命令行参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.hui.t3;

public class Demo02 {
public static void main(String[] args) {
// args.length 数组长度
for (int i = 0; i < args.length; i++){
/**
* java com.hui.t3.Demo02 This is hui
*
* args[0]: This
* args[1]: is
* args[2]: hui
*/
System.out.println("args[" + i + "]: " + args[i]);
}
}
}

可变参数/不定项参数

在方法的声明中,在指定参数类型后加一个省略号(…)。

一个方法中只能指定一个可变参数,它必须是方法的最后一个参数。任何普通参数必须在它之前生命。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.hui.t3;

public class Demo03 {
public static void main(String[] args) {
Demo03 demo03 = new Demo03();
// demo03.test();
demo03.test(1, 2);
demo03.test(1, 2, 3);
}

public void test(int l, int... i){
System.out.println(i[0]);
}
}
  • Title: 方法
  • Author: 茴香豆
  • Created at : 2024-06-02 09:54:09
  • Updated at : 2024-06-02 10:43:47
  • Link: https://hxiangdou.github.io/2024/06/02/Java-3/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments