开发者

Initial value for a instance variable in Java

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 mo开发者_StackOverflow中文版re clearly in a constructor?


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).


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;
}


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).


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)?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜