java中使用相同数量的参数但返回类型不同的方法重写

java中使用相同数量的参数但返回类型不同的方法重写,java,methods,return,overriding,Java,Methods,Return,Overriding,为什么输出如下 class TestOverride{ public int testVlaue(int a,int b){ return a + b; } public float testValue(int x,int y){ return x + y; } public float testValue(float x){ return x; } } public class CodeTest

为什么输出如下

class TestOverride{
    public int testVlaue(int a,int b){
        return a + b;
    }

    public float testValue(int x,int y){
        return x + y;
    }

    public float testValue(float x){
        return x;
    }
}
public class CodeTester{
    public static void main(String a[]){
        TestOverride objTest = new TestOverride();
        System.out.println(objTest.testValue(2));
        System.out.println(objTest.testValue(2,3));
    }
}
它还可以将返回值5的返回类型改为int而不是float?

如果要进行重载,必须更改其中一点的方法签名:

参数类型。 参数数量。 方法中声明的参数的顺序。 返回类型不被视为方法签名之一,因此如果您有两个具有相同名称和不同返回类型的方法,则将出现编译错误,不允许这样做

最后,在您的代码中有两个名称不同的方法,因此没有编译错误,您可以调用返回float的方法

查看vl和va中的不同

testVlaue 测试值


调用System.out.printlnobjTest.testValue2,3;第二个

你想怎么做?Java如何知道要执行哪个函数?它执行第一次匹配。基本上,这种编程在很多方面都是错误的。不要把你的问题隐藏在代码的注释中。不清楚您在问什么。@RDC如果要编辑,请编辑。修复一切。不仅仅是一个字符。qestion是关于重写,而不是重载。
2.0
5.0