I am a Java programmer who is currently reading GoF book on design patterns where examples are given in C++ and Smalltalk syntax . I came across a particular syntax in C++ which I found out to be called member initialization list . From the answers given it seems like using member initialization list is a good practice(much more efficient) than using assignments for member variables .Is there something similar in Java ? If not then there should be a good reason why Java designers didn't incorporate this feature . What are your thoughts on the same ?
Asked
Active
Viewed 3,737 times
6
-
3My understanding of Java is severely limited, so someone please correct if what I say about it is wrong: In Java, member variables are either references, which are cheap to copy, or simple datatypes, like int and double, which are also cheap to copy. So you're not losing much if anything by default initializing a variable, then assigning a new value to it. Whereas in C++, objects can have very expensive default initialization. And if you're just going to overwrite the old value, that default initialization was a huge waste. – Benjamin Lindley Feb 02 '13 at 17:42
-
In addition, some objects in C++ cannot be default initialized, and the initialization list is a necessity in those situations. – Benjamin Lindley Feb 02 '13 at 17:48
-
1This question was answered in detail here: http://stackoverflow.com/questions/7154654/why-doesnt-java-have-intializer-lists-like-in-c – Bogdan Feb 02 '13 at 17:56
2 Answers
4
The reasons why it's necessary in C++ thankfully don't apply to Java.
Fields are only references or primitives so you don't need to worry that you're constructing the field objects and performing assignment operations on them.
Java allows assignment of final fields exactly once in constructor bodies (though the specification of this is quite verbose).

Tom Hawtin - tackline
- 145,806
- 30
- 211
- 305
1
No, you need to initialize members in their declaration, the constructor(s), or in an initialization method called from constructors.
(Assuming the members need initialization beyond their default values.)

Dave Newton
- 158,873
- 26
- 254
- 302
-
1@Geek It may be more "efficient" in C++, but that's totally irrelevant to Java, since Java isn't C++. As far as guessing Java's original intents, that's mostly OT to SO--but I imagine it was part of the "simpler C++" nature of Java. – Dave Newton Feb 02 '13 at 17:36