1

In Java, unlike in C++, we can provide an initial value for a field in its declaration:

public class BedAndBreakfast {

    public int capacity = 10;  //initialize to 10

    private boolean full = false;  //initialize to false
}

Why was there a need to allow this while it can be done more clearly in a constructor?

1
  • 2
    How exactly is it "more clearly" when done in the constructor? Commented Jan 28, 2010 at 12:16

4 Answers 4

7

Why was there a need to allow this while it can be done more clearly in a constructor?

Which is a highly subjective statement. Obviously the Java developers felt differently (as do I, for one).

Sign up to request clarification or add additional context in comments.

Comments

6

It is clearer if you define the default value with the property. If you have multiple constructors, you will have to define the values in each constructor, which is ugly.

Ultimately, the compiler puts these values in each constructor, so the net result is the same. It's just more readable and easy to support this way.

Update: As BalusC noted in his comment, you can use an initializer block, which is again appended to each constructor by the compiler:

{ 
  var1 = 10;
  var2 = false;
}

1 Comment

Alternatively, you can use the initializer block for this, so that you don't need to copy it over in all constructors.
1

Many people consider it to be clearer that way, the values goes together with the declaration.

Also, the order differs, as these assignments will go before the constructor begins (except the special first constructor line, of course).

Comments

1

To add to what other posted have written... Consider that C++ also allows specifying certain variables' values inline:

const unsigned MAX_SPEED = 85;

In Java, the parallel is a static final variable:

static final int MAX_SPEED = 85;

Sure, even static final variables' values can be assigned separate from their declarations:

static final int MAX_SPEED;

static {
  MAX_SPEED = 85;
}

But my point is that once some types of variables' assignments are allowed in declaration, why not allow all (from a language design point of view)?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.