【发布时间】:2019-03-21 14:19:24
【问题描述】:
假设我有两种方法
public void methodA(int a, int b, int c, int d, int e){
//Some logic
anotherMethodA(a, b, c, d, e);
}
public void methodA(int a, int b, int c){
//Exactly the same logic but with only three parameters
anotherMethodA(a, b, c);
}
//anotherMethodA and anotherMethodA also have the same logic but applied to a different number of parameters.
当逻辑变得有点复杂时,它看起来像很多重复的代码。
有没有办法用另一种方式写这个?
编辑:如果参数类型不同怎么办? (a、b、c、d、e 不都是整数)
【问题讨论】:
-
这里为什么需要重载?直接调用相应的方法即可。
-
如果你正在使用,
d, e你不能有完全相同的逻辑。你能在你的代码中发布你是如何使用 d, e 的吗? -
anotherMethodA 和 anotherMethodB 长什么样子?
-
也许你应该有一个 anotherMethod 以整数数组作为参数。很难说不知道它的作用以及 a、b、c、d 和 e 是什么。
-
使用参数对象并将你的逻辑存储到同一个方法中
标签: java methods overloading