Java make one method return an int OR a string and require a String and a String or an int and a String

huangapple go评论64阅读模式
英文:

Java make one method return an int OR a string and require a String and a String or an int and a String

问题

例如,如果我有这个方法:

public static String exampleMethod(String a, String b) {
}

是否可能创建一个相同名称的类似方法,如下所示:

public static String exampleMethod(String a, int b) {
}

而且 exampleMethod 是否可以返回 int 或者 string

英文:

For example if I had the method:

public static String exampleMethod(String a, String b) {
    }

Is it possible to make the same method with the same name like this:

public static String exampleMethod(String a, int b) {
    }

And is it possible for exampleMethod to return either a int or a string?

答案1

得分: 1

  1. 是的,这被称为方法重载。
  2. 不,你不能从同一个方法中返回不同的返回类型。你能做的最好的方式是同时返回它们,并让调用者检查你返回了哪个。例如,创建一个元组类来存储字符串和整数:Tuple<String, Integer>,然后从你的方法中返回它。
英文:
  1. Yes, it's called method overloading.
  2. No, you cannot return different return types from the same method. The best you can do is to return both and have the caller check which you've returned. i.e. create a tuple class to store the String and Integer: Tuple<String, Integer>, and return it from your method.

答案2

得分: 0

是的,这被称为方法重载。一个方法只能有一个返回类型,但通过重载,每个版本的方法可以有自己的返回类型。

英文:

Yes, it's called method overloading. A method can only have one return type, but by overloading, each version of the method can have its own return type.

答案3

得分: 0

这被称为方法重载。
如果您希望您的方法接受两个字符串或一个字符串和一个整数:

public static String exampleMethod(String a, int b) {
}

如果您希望它接受两个字符串:

public static String exampleMethod(String a, String b) {
}

等等...
不幸的是,一个方法不能有两个返回类型,但在重载时,您可以更改返回类型。例如:

public static int exampleMethod(String a, int b) {
}
英文:

This is called Method Overloading.
If you want your method to accept two strings or a string and an int:

public static String exampleMethod(String a, int b) {
    }

If you want it to accept two strings:

public static String exampleMethod(String a, String b) {
    }

etc...
Unfortunately, one method cannot have two return types but when overloading, you can change the return type. For example:

 public static int exampleMethod(String a, int b) {
    }

huangapple
  • 本文由 发表于 2020年8月18日 20:36:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/63468768.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定