0

I was reading the Java Tutorial and had a question about explicit constructor invocation. First of all, here are the fields and constructors as written in the tutorial, plus another constructor I added:

private int x, y;
private int width, height;

public Rectangle() {
    this(0, 0, 1, 1);
}

public Rectangle(int width, int height) {
    this(0, 0, width, height);
}

public Rectangle(short x, short y, int width, int height) {
    this.x = (int) x+4;
    this.y = (int) y+4;
    this.width = width;
    this.height = height;
}

public Rectangle(int x, int y, int width, int height) {
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
}

In the default constructor, "this(0,0,1,1);" line doesn't specify the types of the 0s. My question is, why doesn't it go to the third constructor I wrote (with 'short' types) or give errors. When I print out the object's 'x' value, I always get 0 and never 4. How does Java decide to go with the 'int'?

degemenc
  • 481
  • 4
  • 10

1 Answers1

1

In the default constructor, "this(0,0,1,1);" line doesn't specify the types of the 0s

That's an incorrect statement. Integral numeric literals (having no suffix), are always ints (which is why a literal such as 3000000000 would be compilation error, since that value is too large for an int). Therefore the last constructor - Rectangle(int x, int y, int width, int height) - is chosen.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • Okay, but when I modify the default constructor as "this( (short) 0, (short) 0, 1, 1);" it still goes to the last constructor. – degemenc Mar 08 '18 at 06:56
  • 1
    @DerivedEngineer no, `this( (short) 0, (short) 0, 1, 1)` would invoke the `Rectangle(short x, short y, int width, int height)` constructor. You must be mistaken. – Eran Mar 08 '18 at 06:59
  • yep, my mistake. Thanks. – degemenc Mar 08 '18 at 07:02