Does null have Object type?
Why does this output: "inside String argument method"? Isn't null "Object" type?
class A {
void printVal(String obj) {
System.out.println("inside String argument method");
开发者_如何转开发 }
void printVal(Object obj) {
System.out.println("inside Object argument method");
}
public static void main(String[] args) {
A a = new A();
a.printVal(null);
}
}
The most specific matching method will be called. More information here:
- Which overload will get selected for null in Java?
Yes, but null is also String type and all other types, so it selects the most specific method to call.
More specifically, a null
literal will call the String version, for the reasons outlined by the other answers.
On the other hand:
class A {
void printVal(String obj) {
System.out.println("inside String argument method");
}
void printVal(Object obj) {
System.out.println("inside Object argument method");
}
public static void main(String[] args) {
A a = new A();
Object myObj = null;
a.printVal(myObj);
}
}
will print "inside Object argument method." As will settings the type for myObj
to any type other than String
.
精彩评论