Java中重载和方法返回类型的关系?

编程入门 行业动态 更新时间:2024-10-26 03:28:26
本文介绍了Java中重载和方法返回类型的关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如果有两个方法,它们的参数不同,返回类型不同.像这样:

If there are two methods, they have different parameters, and their return types are different. Like this:

int test(int p) { System.out.println("version one"); return p; } boolean test(boolean p, int q) { System.out.println("version two"); return p; }

如果返回类型相同,当然是重载.但是由于返回类型不同,我们还能认为这是过载吗?

If the return types are same, of course this is overload. But since the return types are different, can we regard this as overload still?

推荐答案

考虑以下几点进行重载:

consider following points for overloading:

  • 在java中重载方法的首要规则是改变方法签名.方法签名由参数个数、参数类型和参数顺序组成(如果它们是不同类型的).​​

  • First and important rule to overload a method in java is to change method signature. Method signature is made of number of arguments, type of arguments and order of arguments if they are of different types. public class DemoClass { // Overloaded method public Integer sum(Integer a, Integer b) { return a + b; } // Overloading method public Integer sum(Float a, Integer b) { //Valid return null; } }

  • 方法的返回类型从来不是方法签名的一部分,所以只改变方法的返回类型并不等同于方法重载.

  • Return type of method is never part of method signature, so only changing the return type of method does not amount to method overloading.

    public class DemoClass { // Overloaded method public Integer sum(Integer a, Integer b) { return a + b; } // Overloading method public Float sum(Integer a, Integer b) { //Not valid; Compile time error return null; } }

  • 在重载方法时也不考虑从方法中抛出的异常.因此,您的重载方法会抛出相同的异常、不同的异常或根本不抛出任何异常;对方法加载完全没有影响.

  • Thrown exceptions from methods are also not considered when overloading a method. So your overloaded method throws the same exception, a different exception or it simply does no throw any exception; no effect at all on method loading.

    public class DemoClass { // Overloaded method public Integer sum(Integer a, Integer b) throws NullPointerException{ return a + b; } // Overloading method public Integer sum(Integer a, Integer b) throws Exception{ //Not valid; Compile time error return null; } }

  • 更多推荐

    Java中重载和方法返回类型的关系?

    本文发布于:2023-06-11 23:29:15,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/645255.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:类型   关系   方法   Java

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!