什么叫方法重载?

方法重载:指在同一个类中,允许存在一个以上的同名方法,只要它们的参数列表不同即可,与修饰符和返 回值类型无关。

怎么区分方法是否重载

  • 是否在同一个类当中
  • 参数列表:个数不同,数据类型不同,顺序不同。

重载方法调用:JVM通过方法的参数列表,调用不同的方法。

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

案例代码

需求:比较两个数据是否相等。参数类型分别为两个 byte 类型,两个 short 类型,两个 int 类型,两个 long 类型,并 在 main 方法中进行测试。

package com.wu.day04.demo2;

public class Method_Demo6 {

    public static void main(String[] args) {
   //定义不同数据类型的变量
        byte a = 10;
        byte b = 20;
        short c = 10;
        short d = 20;
        int e = 10;
        int f = 10;
        long g = 10;
        long h = 20;
      // 调用
        System.out.println(compare(a, b));
        System.out.println(compare(c, d));
        System.out.println(compare(e, f));
        System.out.println(compare(g, h));
    }

    // 两个byte类型的
    public static boolean compare(byte a, byte b) {
        System.out.println("byte");
        return a == b;
    }

    // 两个short类型的
    public static boolean compare(short a, short b) {
        System.out.println("short");
        return a == b;
    }

    // 两个int类型的
    public static boolean compare(int a, int b) {
        System.out.println("int");
        return a == b;
    }

    // 两个long类型的
    public static boolean compare(long a, long b) {
        System.out.println("long");
        return a == b;

    }
}

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄