【问题标题】:Checking for valid overloading [duplicate]检查有效的重载[重复]
【发布时间】:2015-02-23 15:01:14
【问题描述】:

我想知道这是否是一个有效的重载:

public class OverLoadingTest{

     private void callFunction(Object object){
              System.out.println("Printing Object");
     }

     private void callFunction(String string){
              System.out.println("Printing String");
     }

}

更进一步,因为有人问我这个问题。 如果我喜欢这样,

OverLoadingTest test = new OverLoadingTest();
test.callFunction(null);

将打印什么?

当然,我认为它根本不是有效的重载。 所以第二部分没有问题。

请用一些解释告诉我。

【问题讨论】:

  • @FastSnail - 不。它将使用 String 参数调用方法
  • 是的,我错了。我忘记了最小的可能性

标签: java oop overloading


【解决方案1】:

调用具有最少通用参数的方法。因此,在您的情况下,它将是接受 String

的方法

注意:如果 2 个类处于同一级别,那么您将收到 模糊调用 异常。例如,如果一种方法采用String,另一种采用Exception

【讨论】:

  • 能否解释一下最后一行if one method took String and another took Exception
  • @Shail016 - 请参阅,如果 2 个类在 类层次结构 中处于 不同 级别,则 较低 级别将选择班级。因此,如果参数是IOExceptionException,则将打印IOException,因为它是Exception子类最不通用的)。同样的概念适用于StringObject。因为StringObject子类。现在,如果您有IOExceptionInterruptedException,那么调用将是不明确,因为这两个类都在同一级别。明白了吗?
  • 此外,类必须在它们之间有关系。 FileNotFoundExceptionString 将给出 compile-time 错误
【解决方案2】:
If more than one member method is both accessible and applicable to a method 
invocation, it is necessary to choose one to provide the descriptor for 
the run-time method dispatch.
The Java programming language uses the rule that the most specific method is chosen.

JSL 15.12.2.5查看更多详情

  • 在您的情况下,将调用 String 方法,如果参数是 Stringnull,并且对于其他参数类型,将调用 Object 方法。
  • 在您的示例中,如果您定义了一个参数类型不是String(例如整数)的方法,则无法编译源代码,因为在String 和@987654328 的方法之间调用不明确@ 因为他们是同一级别的。

【讨论】:

    猜你喜欢
    • 2014-02-02
    • 2014-08-17
    • 2010-10-23
    • 2013-07-17
    • 2014-04-13
    • 2011-08-26
    • 2020-08-18
    • 2013-04-11
    • 1970-01-01
    相关资源
    最近更新 更多