Question

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 ?

Was it helpful?

Solution

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top