您的位置:首页 > 移动开发 > Objective-C

回复:null是什么数据类型

2007-03-26 15:28 477 查看
例1

码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

Test2
    method(Object o)
    System.out.println();
  
  
    method(String s)
    System.out.println();
  
  
    
     main(String[] args)
    Test2 test =  Test2();
    test.method();
  

编译通过了,而且运行时也没有错误,问题是null到底是什么数据类型,或者说java如何进行转型的 
 

答  

1. String   是 Object 的子类 。所以函数在调用时优先选择作为子类的String。 运行结果是String Version。

2. 若没有返回为String 的 test 函数,则函数调用 超类 的Object 对象。 运行结果为Object Version。

例2

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
1516
17
18
19

Tester
test(Object s)     System.out.println ();
test(Tester s)     System.out.println ();
test(SubTester s)  System.out.println ();
 

 
main (String args[])
Tester c =  Tester ();

c.test ();
c.test ( Object());

 
SubTester  Tester

 c.test (null);

即 test 在调用函数时优先选择作为子类的子类的 SubTester   所以运行结果是SubTester version。

例3

Test2
 
method(Object o)
System.out.println();

method(String s)
System.out.println();

method( s)
System.out.println();

main(String[] args)
Test2 test =  Test2();
Object o =  Object();
test.method((Object));
test.method();

那么第一个method方法是会打出object version的,而第二个method则会出现编译错误,这又是怎么回事呢?
很明显,String s  与 StringBuffer s   都是Object 的子类,地位相同,所以造成冲突。

 

同理 在例2 中加入void test( String s) {System.out.println("String Version");}

也会引起冲突,造成编译错误

 

 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息