Medardas
Medardas

Reputation: 540

How is it possible to supply Integer to setter expecting double?

I have this snippet:

class scratch_5{
  public static void main(String theory[]){
    Item i = new Item();
    Integer a = 3;
    i.setNum(a);
    System.out.println(i.getNum());
  }

}

class Item{
   double num;

   public void setNum(double num){this.num=num;}
   public double getNum(){return num;}
}

Can you explain to me how is this possible? I understand that double wrapper class is Double, and both Integer and Double are derived from Number, hence they shouldn't be possible to use interchangeably

Upvotes: 0

Views: 106

Answers (1)

Bohemian
Bohemian

Reputation: 425198

It compiles because Integer is unboxed to an int, which is then safely widened to double.

According to Section 5.1.2 of the JLS: Widening primitive conversions:

19 specific conversions on primitive types are called the widening primitive conversions:
...
int to long, float, or double
...
Despite the fact that loss of precision may occur [in some conversions], a widening primitive conversion never results in a run-time exception


What you couldn't do is the opposite:

class Item {
    public void setNum(Double num) {...}
}

int a = 3;
i.setNum(a);   // compile error

Java won't widen and autobox.

Upvotes: 5

Related Questions