Home:ALL Converter>Facing ambiguity in spring constructors, second constructor is getting called

Facing ambiguity in spring constructors, second constructor is getting called

Ask Time:2021-09-22T05:51:25         Author:Dawson Smith

Json Formatter

I'm facing an issue which is producing an output which is not exactly per the norm. I have read that in case of constructor ambiguity the first constructor gets called. But I'm facing a completely different issue.

My class -

public class Addition {
    private int a;
    private int b;
    public Addition() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    public Addition(int a, int b) {
        super();
        this.a = a;
        this.b = b;
        System.out.println("Constructor : int, int");
    }
    
    public Addition(double a, double b) {
        super();
        this.a = (int)a;
        this.b = (int)b;
        System.out.println("Constructor : double, double");
    }
    
    public void doSum() {
        System.out.println("Sum is -> "+(this.a+this.b));
    }

    @Override
    public String toString() {
        return "Addition [a=" + a + ", b=" + b + "]";
    }
    
}

XML file -

<bean class="com.spring.Addition" name="addition1">
    <constructor-arg>
    <value>12</value>
    </constructor-arg>
    <constructor-arg>
    <value>34</value>
    </constructor-arg>
    </bean>

Main code -

Addition addition = (Addition)applicationContext.getBean("addition1");
System.out.println(addition);

Output-

Constructor : double, double
Addition [a=12, b=34]

My only concern here is why is the second constructor getting called here, when (int,int) constructor is defined before the (double,double) constructor?

Author:Dawson Smith,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/69275923/facing-ambiguity-in-spring-constructors-second-constructor-is-getting-called
yy