【问题标题】:Correct way to work with overloading methods in Java [closed]在 Java 中使用重载方法的正确方法 [关闭]
【发布时间】: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


【解决方案1】:

您可以使用的另一个工具是使用... 的可变数量的参数。根据您的逻辑,您可以使用这些方法中的任何一种。过度使用会给你带来麻烦。

【讨论】:

  • 我在问我的问题时尽量笼统,但在我的具体情况下,它们并不都是整数。否则 vararg 确实可以工作。
  • 当您说“这是相同的逻辑但应用于不同数量的参数”时,这个问题很难理解。您必须给出逻辑示例,然后我们才能提出解决方案。
猜你喜欢
  • 1970-01-01
  • 2023-03-02
  • 2015-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-02
  • 2013-06-27
相关资源
最近更新 更多