分享

Java|Java世界_中文论坛|ChinaJavaWorld技术论坛 : 有谁知道nul...

 ShangShujie 2006-11-18
Q. How does Java compiler resolve the ambiguity to decide which methods to call?
A:
In the following example, four test() methods, if we pass ambiguous \b{null} to the test, which one should (will) be called? The 3 on top has super/subclass/sub-subclass relationship. The most specific one (down hierarchy) will be called. The 4th with String as a parameter, but it is a sibling of Tester. Ambiguity compile time error results.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Tester {
            void test(Object s)    { System.out.println ("Object version");    }
            void test(Tester s)    { System.out.println ("Tester version");    }
            void test(SubTester s) { System.out.println ("SubTester version"); }
             
            // Not compilable any more if you uncomment the line 
            // since String and Tester are siblings
            // void test(String s) { System.out.println ("String version"); } 
             
            public static void main (String args[]) {
            Tester c = new Tester ();
            // Ambiguous, the most specific one which fit will be call
            c.test (null);         // SubTester version 
            c.test (new Object()); // Object version 
            }
            }
             
            class SubTester extends Tester{
            }
            


引用原文:
Quotation from JLS2

"The informal intuition is that one method declaration is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error."

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约