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

2022/6/29 23:20:26

本文主要是介绍方法重载的注意事项和练习题四种不同参数类型的方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

方法重载的注意事项

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

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

 



这篇关于方法重载的注意事项和练习题四种不同参数类型的方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程