回复:null是什么数据类型
来源:互联网 发布:服务端源码是什么 编辑:程序博客网 时间:2024/05/02 01:00
例1
码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Test2 { public void method(Object o) { System.out.println("Object Version"); } public void method(String s) { System.out.println("String Version"); } public static void main(String[] args) { Test2 test = new Test2(); test.method(null); }}
编译通过了,而且运行时也没有错误,问题是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
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{ }
c.test (null);
即 test 在调用函数时优先选择作为子类的子类的 SubTester 所以运行结果是SubTester version。
例3
public class Test2 { public void method(Object o) { System.out.println("Object Version"); } public void method(String s) { System.out.println("String Version"); } public void method(StringBuffer s) { System.out.println("StringBuffer Version"); } public static void main(String[] args) { Test2 test = new Test2(); Object o = new Object(); test.method((Object)null); test.method(null); }}
那么第一个method方法是会打出object version的,而第二个method则会出现编译错误,这又是怎么回事呢?
很明显,String s 与 StringBuffer s 都是Object 的子类,地位相同,所以造成冲突。
同理 在例2 中加入void test( String s) {System.out.println("String Version");}
也会引起冲突,造成编译错误
- 回复:null是什么数据类型
- NULL是什么
- NULL是什么?
- NULL到底是什么
- Java中的Null是什么?
- null 是什么类型的
- 回复《PHP的弱点,缺点是什么?》
- 回复《PHP的弱点,缺点是什么?》
- NULL的数据类型
- Java数据类型Null判断
- null的数据类型
- DWORD是什么数据类型啊?
- sysname数据类型是什么
- _variant_t 是什么数据类型??
- sysname 数据类型是什么
- uint8_t是什么数据类型
- uint8_t是什么数据类型
- uint8_t是什么数据类型
- Hibernate级联保存和更新
- 日语小说连载_2
- 大阪第7天
- Oracle10g中的4种数据存储方式
- linux目录架构
- 回复:null是什么数据类型
- .net面试问题归纳
- 如何编写 Windows Mobile Smartphone 录音程序
- SQL Server中索引使用及维护
- C#.Net的常见面试试题
- 深入浅出工厂模式
- 简介vc中的release和debug版本的区别(转)
- 测试12
- 日语小说连载_3