在Java中使用重载方法的正确方法
假设我有两种方法在Java中使用重载方法的正确方法,java,methods,overloading,Java,Methods,Overloading,假设我有两种方法 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); } //an
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是什么,很难说。使用参数对象并将逻辑存储到相同的方法中。我在问问题时尽量笼统,但在我的特定情况下,它们并不都是整数。否则vararg确实会工作。当您说它是相同的逻辑,但应用于不同数量的参数时,问题很难理解。你必须给出一个逻辑的例子,然后我们可以提出一个解决方案。