0
点赞
收藏
分享

微信扫一扫

Java日常练习:方法重载

小典典Rikako 2022-02-13 阅读 150
package src.test;
/*
 * 方法重载
 *   多个方法在同一个类中
 *   多个方法具有相同的方法名
 *   多个方法的参数不相同,类型不同或者数量不同
 *
 *  与返回值无关
 *  在调用的时候,java虚拟机会通过参数的不同来起飞同名的方法
 */

public class 方法重载 {
    public static void main(String[] args) {
        //调用方法
        int result = sum(10, 20);
        System.out.println(result);

        double result2 = sum(10.0, 20.0);
        System.out.println(result2);

        int result3 = sum(10, 20, 30);
        System.out.println(result3);
    }

    //需求1.求两个int类型数据和的方法
    public static int sum(int a, int b) {
        return a + b;
    }

    //需求2.求两个double类型数据和的方法
    public static double sum(double a, double b) {
        return a + b;
    }

    //需求3.求三个int类型数据和的方法
    public static int sum(int a, int b, int c) {
        return a + b + c;
    }
}

在这里插入图片描述

扩展练习

package src.test;

/*
 * 需求:使用方法重载的思想,
 * 设计比较两个整数是否相同的方法,兼容全整数类型
 * 思路:1.定义比较两个数中的是否相同的方法compare()方法,参数选择两个int类型参数
 *      2.定义对应的重载方法,变更对应的参数类型,参数变更为两个long类型参数
 *      3.定义所有的重载方法,两个byte类型与两个short类型参数
 *      4.完成方法的调用,测试运行结果
 * */


public class 方法重载的练习 {

    public static void main(String[] args) {
        System.out.println(compare(10, 20));
        System.out.println();
        System.out.println(compare((long) 10, (long) 20));
        System.out.println();
        System.out.println(compare((byte) 10, (byte) 20));
        System.out.println();
        System.out.println(compare((short) 10, (short) 20));

    }

    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(byte a, byte b) {
        System.out.println("byte");
        return a == b;
    }

    public static boolean compare(short a, short b) {
        System.out.println("short");
        return a == b;
    }
}

在这里插入图片描述

举报

相关推荐

0 条评论