简体   繁体   English

为什么`System.out.println(null);`give“方法println(char [])对于类型PrintStream错误是不明确的”?

[英]Why does `System.out.println(null);` give “The method println(char[]) is ambiguous for the type PrintStream error”?

I am using the code: 我正在使用代码:

System.out.println(null);

It is showing the error: 它显示错误:

The method println(char[]) is ambiguous for the type PrintStream

Why doesn't null represent Object ? 为什么null不表示Object

There are 3 println methods in PrintStream that accept a reference type - println(char x[]) , println(String x) , println(Object x) . PrintStream中有3个println方法接受引用类型 - println(char x[])println(String x)println(Object x)

When you pass null , all 3 are applicable. 传递null ,所有3都适用。 The method overloading rules prefer the method with the most specific argument types, so println(Object x) is not chosen. 方法重载规则更喜欢具有最特定参数类型的方法,因此不选择println(Object x)

Then the compiler can't choose between the first two - println(char x[]) & println(String x) - since String is not more specific than char[] and vice versa. 然后编译器不能在前两个之间进行选择 - println(char x[])println(String x) - 因为String不比char[]更具体,反之亦然。

If you want a specific method to be chosen, cast the null to the required type. 如果要选择特定方法,请将null转换为所需类型。

For example : 例如 :

System.out.println((String)null);

If you call System.println(null) there are multiple candidate methods (with char [] , String and Object argument) and the compiler can't decide which one to take. 如果调用System.println(null)则有多个候选方法(使用char []StringObject参数),编译器无法决定采用哪一个。

Fix 固定
Add an explicit cast to null. 将显式强制转换添加到null。

System.out.println((Object)null);

Or use null object pattern . 或者使用null对象模式


Why does't null represent Object? 为什么null不代表Object?

From JLS 4.1 The Kinds of Types and Values JLS 4.1类型和价值的种类

There is also a special null type, the type of the expression null, which has no name. 还有一个特殊的null类型,表达式的类型为null,没有名称。
Because the null type has no name, it is impossible to declare a variable of the null type or to cast to the null type. 由于null类型没有名称,因此无法声明null类型的变量或转换为null类型。
The null reference is the only possible value of an expression of null type. 空引用是null类型表达式的唯一可能值。 The null reference can always be cast to any reference type. null引用始终可以强制转换为任何引用类型。
The null reference can always be assigned or cast to any reference type 始终可以将null引用分配或强制转换为任何引用类型

In practice, the programmer can ignore the null type and just pretend that null is merely a special literal that can be of any reference type 在实践中,程序员可以忽略null类型,只是假装null只是一个特殊的文字,可以是任何引用类型

So the type of null is not Object , though it can be converted to (read-as assigned to) an Object . 因此null的类型不是 Object ,尽管它可以转换为(读取 - 分配给) Object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM