Geek
Geek

Reputation: 27209

Is there member initialization list syntax in Java like C++?

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 ?

Upvotes: 6

Views: 4040

Answers (2)

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

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

Upvotes: 4

Dave Newton
Dave Newton

Reputation: 160271

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

Upvotes: 1

Related Questions