Reputation: 12013
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?
Upvotes: 1
Views: 591
Reputation: 13374
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)?
Upvotes: 1
Reputation: 597106
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;
}
Upvotes: 6
Reputation: 545588
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).
Upvotes: 7
Reputation: 24159
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).
Upvotes: 1