方法重载的注意事项和练习题四种不同参数类型的方法


方法重载的注意事项

方法重载与下列因素相关:

1.参数个数不同
2.参数类型不同
3.参数的多类型顺序不同方法重载与下列因素无关:1与参数的名称无关
2.与方法的返回值类型无关

 public static int sum(int a, int b) {
        System.out.println("有2个参数的方法执行!");
        return a + b;
    }
//     错误写法!与方法的返回值类型无关
//    public static doub1e sum(int a,int b) {
//        return a + b + 0.0;
//}

    // 错误写法!与参数的名称无天
//    public static int sum (int x, int y) {
//        return x + y;
//    }

    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("有3个参数的方法执行!");
        return a + b + c+d;
    }
    public static int sum( int a, double b) {
        return (int) (a + b);
    }
    public static int sum( double a, int b) {
        return ( int) (a + b);
    }

 

 

练习题四种不同参数类型的方法

比较两个数据是否相等。

参数类型分别为两个byte类型,两个short类型,两个int类型,两个Long类型,

并在main方法中进行测试。

public static void main(String[] args) {
        byte a = 10;
        byte b = 20;
        System.out.println(isSame(a,b));
        System.out.println(isSame((short) 20,(short) 20)) ;
        System.out.println(isSame(11,12));
        System.out.println(isSame(10L,10L));
}
    public static boolean isSame(byte a, byte b) {
        boolean same;
        if (a == b) {
            same = true;
        }else {
            same = false;
        }
            return same;
        }
    public static boolean issame( short a, short b) {
        boolean same = a == b ? true : false;
        return same;
    }
    public static boolean isSame(int a, int b) {
        return a == b;
    }
    public static boolean isSame( long a, long b) {
        if (a == b) {
            return true;
        } else {
            return false;
        }
    }

 

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/270716.html

(0)
上一篇 2022年6月29日
下一篇 2022年6月29日

相关推荐

发表回复

登录后才能评论