Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

java - Understanding which constructor is chosen and why

Why following program every time prints I'm string and not I'm object. or I'm int.?

public class Demo {

    public Demo(String s){
        System.out.println("I'm string");
    }

    public Demo(int i){
        System.out.println("I'm int.");
    }

    public Demo(Object o){
        System.out.println("I'm object.");
    }

    public static void main(String[] args) {
        new Demo(null);
    }
}

Also if I replace int with Integer. It gives error as The constructor Demo(String) is ambiguous. Why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

null can be converted to Object or String, but not int. Therefore the second constructor is out.

Between the conversion to Object or the conversion to String, the conversion to String is more specific, so that's what's picked.

The JLS section 15.12.2 describes method overload resolution, and I believe the same approach is used for constructor resolution. Section 15.12.2.5 describes choosing the most specific method (constructor in this case):

The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.

This about the constructor invocation with Object or String arguments - any invocation handled by new Demo(String) could also be passed on to new Demo(Object) without a compile-time type error, but the reverse is not true, therefore the new Demo(String) one is more specific... and thus chosen by the overload resolution rules.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...