方法的重载(Overload)+ println重载

方法的重载(Overload)

package cn.day01;

/*方法的重载(Overload):多个方法的名称一样,但是参数列表不一样。
 * 好处:只需要记住唯一一个方法名称,就可以实现类似多个功能
 *
 * 方法重载与下列因素有关:
 * 1.参数个数不同
 * 2.参数类型不同
 * 3。参数的多类型顺序不同
 *
 * 方法重载与下列因素无关:
 * 1.与参数的名称无关
 * 2.与方法的返回值类型无关
 * 
 * Tips:
 * byte short int long float double char boolean 
 * String
 * 在调用输出语句的时候,println方法其实是进行了多种数据类型的重载形式。
 * */
public class MethodOverload {
    public static void main(String[] args) {
        System.out.println(sum(10, 20));
        System.out.println(sum(10, 20, 30));
        System.out.println(sum(10, 20, 30, 40));
        //System.out.println(sum(10,20,30,40,50));
    }

    public static int sum(int a, int b) {
        System.out.println("两个参数");
        return a + b;
    }
//错误写法!与方法的返回值类型无关
   /* public static double sum(int a, int b) {
        System.out.println("两个参数");
        return a + b + 0.0;
    }*/
    //错误写法!!与参数名称无关
    /* public static int sum(int x, int y) {

        return x + y;
    }*/

    public static int sum(double a, double b) {
//        System.out.println("两个参数");
        return (int) (a + b);
    }

    public static int sum(int a, double b) {

        return (int) (a + b);
    }

    public static int sum(double a, int b) {

        return (int) (a + b);
    }

    public static int sum(int a, int b, int c) {
        System.out.println("3个参数");
        return a + b + c;
    }

    public static int sum(int a, int b, int c, int d) {
        System.out.println("4个参数");
        return a + b + c + d;
    }
}

println重载

例题

package cn.day01;

/*
 * 题目要求:
 * 比较两个数据是否相等。
 * 参数类型分别是两个byte类型,两个short类型,两个int类型,两个long类型,
 * 并在main方法中进行测试。
 * */
public class OverloadSame {
    public static void main(String[] args) {
        byte a = 10;
        byte b= 20;
        System.out.println(isSame(a,b));
        System.out.println(isSame((short) 10,(short) 20));
        System.out.println(isSame(11,12));
        System.out.println(isSame(10L,10L));
    }

    public static boolean isSame(byte a, byte b) {
        System.out.println("两个byte参数的方法执行!");
        boolean same;
        if (a == b) {
            same = true;
        } else {
            same = false;
        }
        return same;
    }

    public static boolean isSame(short a, short b) {
        System.out.println("两个short参数的方法执行!");
        boolean same = a == b ? true : false;
        return same;
    }

    public static boolean isSame(int a, int b) {
        System.out.println("两个int参数的方法执行!");
        return a == b;
    }

    public static boolean isSame(long a, long b) {
        System.out.println("两个long参数的方法执行!");
        if (a == b) {
            return true;
        } else {
            return false;
        }
    }
}

执行结果

两个byte参数的方法执行!
false
两个short参数的方法执行!
false
两个int参数的方法执行!
false
两个long参数的方法执行!
true
posted @ 2021-02-26 16:52  叶梓渔  阅读(144)  评论(0)    收藏  举报