您的位置:首页 > 编程语言 > Java开发

java方法、方法重载

2020-04-07 10:32 369 查看

java方法

一、Java方法

1. 方法声明

[修饰符1 修饰符2 ...]  返回值类型  方法名(形式参数列表) {
语句...
}

2. 方法调用

对象名.方法名(实际参数);
1 public class TestMethod {
2     public static void main(String args[]) {
3         printInfo();
4         int num1 = 2020;
5         int num2 = 30;
6         System.out.printf("%d + %d = %d", num1, num2, add(num1, num2));
7     }
8
9     public static int add(int a, int b) {
10         return a + b;
11     }
12
13     public static void printInfo() {
14         System.out.println("步平凡的博客>>>");
15     }
16 }

 

 

二、Java方法重载

1. 方法重载与方法的区别

  就上方的加法函数add()而言,若想要完成三个数或多个数的加法时,此时就用到方法重载了。

  方法重载可以理解为方法的拓展。

2. 方法重载的条件

  方法重载的名字与原方法名相同,但形式参数列表不同,此处不同体现为参数类型、参数个数。

  更好的理解,看看下面代码吧~~~

public class TestMethodPro {
public static void main(String args[]) {
System.out.printf("1 + 2 = %d\n", add(1, 2));         // 调用方法1
System.out.printf("1 + 2 + 0 = %d\n", add(1, 2, 0));  // 调用方法2
System.out.printf("1.0f + 2 = %d\n", add(1.0f, 2));   // 调用方法3
System.out.printf("1 + 2.0 = %d\n", add(1, 2.0));     // 调用方法4
}

public static int add(int a, int b) { // 方法1
return a + b;
}

public static int add(int a, int b, int c) { // 方法2
return a + b + c;
}

public static int add(float a, int b) { // 方法3
return (int)(a + b);
}

public static int add(int a, double b) { // 方法4
return (int)(a + b);
}
}

 

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java