051 Method Overloading

示例

//CalculateTax method to calculate tax
/*cost <= 20000  then  tax = 10%
cost > 20000 then  tax = 12.5%*/
public void CalculateTax(double percentage = 4.5)
{
    //create local variable
    double t;

    //calculate tax
    if (this.cost <= 20000)
    {
        t = cost * 10 / 100;
    }
    else
    {
        t = cost * percentage / 100;
    }
    tax = t;
}

public void CalculateTax(double cost, double percentage)
{
    //create local variable
    double t;

    //calculate tax
    if (cost <= 50000)
    {
        t = cost * 5 / 100;
    }
    else
    {
        t = cost * percentage / 100;
    }
    tax = t;
}

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
In Java, method overloading refers to the ability to define two or more methods with the same name in a class. The methods must have different parameter lists (i.e., different types or different numbers of parameters). This allows us to use the same method name for different behaviors, depending on the type or number of parameters passed to it. For example, we can define a method called "sum" that takes two integer parameters and returns their sum. We can also define another method called "sum" that takes three integer parameters and returns their sum. When we call the "sum" method, Java will automatically choose the appropriate method based on the number and types of parameters passed to it. Here's an example of method overloading in Java: ``` public class OverloadingExample { public static void main(String[] args) { int a = 5, b = 10, c = 15; double x = 2.5, y = 3.5; System.out.println(sum(a, b)); // calls sum(int, int) System.out.println(sum(a, b, c)); // calls sum(int, int, int) System.out.println(sum(x, y)); // calls sum(double, double) } public static int sum(int a, int b) { return a + b; } public static int sum(int a, int b, int c) { return a + b + c; } public static double sum(double a, double b) { return a + b; } } ``` In this example, we have three "sum" methods with different parameter lists. When we call the "sum" method with two integers, Java will call the first method that takes two integers. When we call the "sum" method with three integers, Java will call the second method that takes three integers. When we call the "sum" method with two doubles, Java will call the third method that takes two doubles.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黄健华Yeah

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值