我需要一个静态方法,只需将两个不同的数字加在一起并返回结果。但是,它需要能够接受不同类型的数字,例如Integer和Doubles,这是我遇到的问题。这是我的主要方法,无法改变。
public static void main(String[] args)
{
Double answer1 = add(2, 7);
Number answer2 = add(new Integer(4), new Double(5.2));
double answer3 = add(8, 1.3);
System.out.println(answer1 + " " + answer2 + " " + answer3);
}
public static Double add(Double num1, Integer num2)
{
return num1 + num2;
}
上面的方法有正确的正文我只是不知道Double在静态之后应该是什么。是否有某种类型适用于双打和整数?
新情况:
public static double add(Number num1, Number num2)
{
return num1 + num2; //error is here
}
答案 0 :(得分:3)
您可以使用公共基类Number
。
public class Test {
public static void main(String[] args) {
int x = 5;
double y = 10;
System.out.println(getDoubleValue(x, y));
}
private static double getDoubleValue(Number x, Number y){
return x.doubleValue() + y.doubleValue();
}
}
输出:
15.0
答案 1 :(得分:1)
public void draw(String s) {
...
}
public void draw(int i) {
...
}
public void draw(double f) {
...
}
public void draw(int i, double f) {
...
}
请查看以下链接
http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html
意味着您必须使用方法重载
答案 2 :(得分:1)
你应该使用方法重载。
Double Foo() // Version with no arguments
{
}
Double Foo(int arg) // Version with a single int
{
}
Double add(Double num1, Integer num2) // Version with integer and double parameters
{
}
答案 3 :(得分:0)
您可以使用方法重载。使用不同的数据类型创建相同的方法:)