Java方法的定义,调用,重载

Java方法的定义,调用,重载

加法方法的定义与调用

package com.LittleWu.Method;
public class Demo01 {
    // main方法
    public static void main(String[] args) {
         int i = add(1, 2);// 实际参数:实际调用传递给他的参数
         System.out.println(i);
    }
    // 加法方法
    public static int add(int a,int b){ // 形式参数:用来定义作用的
        return a + b;
    }
    // 一个方法只完成一个功能,遵循方法的原子性

}

加法方法的重载与注意事项

package com.LittleWu.Method;
import java.util.Scanner;
public class Demo02 {
    public static void main(String[] args) {
        double max = max(2, 23);
        System.out.println(max);
        // Java是值传递
    }
    // 比大小
    public static int max(int a,int b){
        int result = 0;
        if (a>b){
            result = a;
        }else{
            result = b;
        }
        if (a == b){
            System.out.println("a == b");
            return 0; // 终止方法
        }
        return result;
    }
    // 方法重载 方法名字相同
    // 参数列表必须不同(个数,类型,排列顺序)
    public static double max(double a,double b){
        double result = 0;
        if (a>b){
            result = a;
        }else{
            result = b;
        }
        if (a == b){
            System.out.println("a == b");
            return 0; // 终止方法
        }
        return result;
    }
}

附小练习 Java四种加法方法重载

package com.LittleWu.Method;

/***
 * ░░░░░░░░░░░░░░░░░░░░░░░░▄░░
 * ░░░░░░░░░▐█░░░░░░░░░░░▄▀▒▌░
 * ░░░░░░░░▐▀▒█░░░░░░░░▄▀▒▒▒▐
 * ░░░░░░░▐▄▀▒▒▀▀▀▀▄▄▄▀▒▒▒▒▒▐
 * ░░░░░▄▄▀▒░▒▒▒▒▒▒▒▒▒█▒▒▄█▒▐
 * ░░░▄▀▒▒▒░░░▒▒▒░░░▒▒▒▀██▀▒▌
 * ░░▐▒▒▒▄▄▒▒▒▒░░░▒▒▒▒▒▒▒▀▄▒▒
 * ░░▌░░▌█▀▒▒▒▒▒▄▀█▄▒▒▒▒▒▒▒█▒▐
 * ░▐░░░▒▒▒▒▒▒▒▒▌██▀▒▒░░░▒▒▒▀▄
 * ░▌░▒▄██▄▒▒▒▒▒▒▒▒▒░░░░░░▒▒▒▒
 * ▀▒▀▐▄█▄█▌▄░▀▒▒░░░░░░░░░░▒▒▒
 * 单身狗就这样默默地看着你,一句话也不说。
 */

public class Test01 {
    // add方法的重载 (要求整数,浮点两数相加,三数相加四种)
    public static void main(String[] args) {
        int add = add(100, 200);
        double add1 = add(100.3, 200.69);
        int add2 = add(100, 200, 369);
        double add3 = add(100.3, 200.69, 369.666);
        System.out.println(add + "\t" + add1 + "\t" + add2 + "\t" + add3);
    }
    public static int add(int a,int b){
        return (a+b);
    }
    public static double add(double a,double b){
        return (a+b);
    }
    public static int add(int a,int b,int c){
        return (a+b+c);
    }
    public static double add(double a,double b,double c){
        return (a+b+c);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值