Can initialization expressions be used for constructors in Java as in C ++?

I know that in C ++, class constructors can be written with initialization expressions in this form:

class-name(parameters) : initialization-expressions { body }


Is there any analogue to this in Java? If not, why not? As I know that in C ++, initialization expressions make constructor calls more efficient. Is this proactive Java design that improves efficiency, or is it just overkill?


source to share

2 answers

The main purpose of C ++ initialization lists is inefficient, it is for correct initialization of members (since otherwise default initialization would be used, which might not be desirable or possible). If any efficiency is achieved, it has to do with the elimination of unnecessary, expensive default operations that you plan to undo in the body of the constructor. Java does not initialize member objects before the constructor body, other than setting them to Null. Even as the main guy in C ++, I would freely admit that complicating the language for such micro-optimization is not worth it.



This type of initialization is not required in Java because Java has no built-in member objects. Objects are composed of primitive fields and reference fields. Java will never explicitly refer to default constructors for objects (which C ++ does unless you initialize the member object in the member initialization list).



All Articles