Java中方法重载的确切需求 [英] Exact need of Method Overloading in Java

查看:68
本文介绍了Java中方法重载的确切需求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为我发现了很多关于方法重载的例子和结论,但我仍然对我们如何实时使用它感到困惑.

Since I have found so many examples and conclusions about Method Overloading but still I am confusing in real time how we are using it.

首先,方法重载是类级别的活动,这意味着在该类中我们重载了一个名称相同但参数不同的方法,例如

First of all method overloading is a class level activity means within that class we are overloading a method with same name but different arguments like

void sum(int a,int b){System.out.println(a+b);}  
void sum(double a,double b){System.out.println(a+b);} 

在我们像

public static void main(String args[]){  
ClassName obj=new ClassName ();  
obj.sum(10.5,10.5);  
obj.sum(20,20);  
}  

假设我将采用两种不同的方法来代替这个

Suppose instead of this I will take two separate method like

void method1(int a,int b){System.out.println(a+b);}  
void method2(double a,double b){System.out.println(a+b);} 

我会称这两种方法与上面相同

And I will call this 2 methods same as above

public static void main(String args[]){  
ClassName obj=new ClassName (); 
obj.method1(20,20);   
obj.method2(10.5,10.5);  
} 

在这两种方法的情况下,活动是相同的,那么在这种情况下重载/多态的确切需求是什么.

In both the case for both the methods the activities are same then what is the exact need of overloading/polymorphism in this case.

我在某处发现方法重载提高了程序的可读性 任何人都可以指定仅因为这一行我们才使用方法重载.

Somewhere I found that Method overloading increases the readability of the program can anybody please specify that only because of this line we are using method overloading.

谢谢.

推荐答案

假设我们在 Java 中没有方法重载.

Suppose we didn't have method overloading in Java.

代替:

System.out.println("String");
System.out.println(5);
System.out.println('c');
...

我们会有:

System.out.printlnString("String");
System.out.printlnInt(5);
System.out.printlnChar('c');
...

甚至更糟:

System.out.println1("String");
System.out.println2(5);
System.out.println3('c');
...

这两种选择都会降低代码的可读性.

Both alternatives would make the code less readable.

这篇关于Java中方法重载的确切需求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆