开发者

Does null have Object type?

开发者 https://www.devze.com 2023-01-20 05:19 出处:网络
Why does this output: \"inside String argument method\"? Isn\'t null \"Object\" type? class A { void printVal(String obj) {

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消