How does Java pick which overloaded function to call?

后端 未结 4 2060
刺人心
刺人心 2021-01-04 23:54

This is a purely theoretical question.

Given three simple classes:

class Base {
}

class Sub extends Base {
}    

class SubSub extends Sub {
}
         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-05 00:36

    When you have overloaded static methods then it calls that method that is defined immediately in the class which is invoking the method. If however, no method is defined in the calling class then it will invoke the method inherited from its immediate parent class.

    In your case there are two overloaded methods both of which can accept SubSub as parameter. the compiler checks for the most specific match and goes for it. But the most specific match is generally the lowest in the type hierarchy.

    EDITED

    Removed the conflicting statement. Two methods in classes that are at the same type hierarchy level can't be in ambiguous state for the compiler to choose. This ambiguity is possible only in the case of multiple inheritance.

提交回复
热议问题