java方法、方法重载

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);
    }
}

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值