8.4方法的重载

方法重载的概念:

同一个类中的多个方法,出现方法名相同,但是参数列表不同的情况。
参数列表不同:
参数的个数不同
参数的对应数据类型不同
方法签名:方法名+参数列表
方法重载与方法的返回值类型无关

为什么需要方法重载?
当实现的功能相同,但具体的实现方式不同时,我们可以通过定义名称相同,参数(条 件)不同的方法,来更好的识别和管理类中的方法。

public class MethoDemo4 {
    public static void main(String[] args) {
        //4.调用比较俩个int类型的数据
        int a=10;
        int b=10;
        boolean c=compare(a,b);
        System.out.println(c);
        System.out.println();
        //5.调用比较俩个long类型的数据
        long num1=10L;
        long num2=20L;
        boolean d=compare(num1,num2);
        System.out.println(d);
        System.out.println();
        //6.调用比较俩个double类型的数据
        double s1=2.3;
        double s2=5.5;
        boolean e=compare(s1,s2);
        System.out.println(e);

    }
    //1.定义一个方法,比较俩个数据int类型是否相同
    public static boolean compare(int a, int b){
        System.out.println("判断俩个int的类型的数据是否相同");
        return a==b;
    }
    public static boolean compare(long a, long b) {
        System.out.println("判断俩个long的类型的数据是否相同");
        return a == b;
    }
    public static boolean compare(double a,double b){
        System.out.println("判断俩个double类型的数据是否相同");
        return a==b;
    }
}

声明:本人是一名在学生,写博客是为了加深印象当作笔记之用,不是专业人员,有错误之处,还请大佬不吝赐教

猜你喜欢

转载自blog.51cto.com/15138685/2666232
今日推荐