Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can initialization expressions be used for constructors in Java like 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 some sort of analog to this in Java? If not, then why not? Because I know that in C++, initialization expressions make constructor calls more efficient. Is such an efficiency-booster overlooked by Java's design, or is it just unnecessary?

like image 934
sirsuripu Avatar asked Jan 29 '26 03:01

sirsuripu


1 Answers

The primary purpose of C++ initialization lists is not efficiency, it is for initializing the members correctly (because otherwise default initialization will be used, which may be either undesirable, or impossible). If there is any efficiency gained, it is due to eliminating unnecessary expensive default construction operations which you plan to undo in the constructor body. Java doesn't initialize member objects before the constructor body, other than setting them to Null. Even as a mainly C++ guy, I would freely admit that complicating the language for such a micro-optimization is not worth it.

like image 108
Benjamin Lindley Avatar answered Jan 31 '26 17:01

Benjamin Lindley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!