Initialization in definition vs. initialization in constructor [duplicate]

元气小坏坏 提交于 2019-12-01 22:17:11

The initialization order is matter here.

  1. Set fields to default initial values (0, false, null)
  2. Call the constructor for the object (but don't execute the body of the constructor yet)
  3. Invoke the constructor of the superclass
  4. Initialize fields using initializers and initialization blocks
  5. Execute the body of the constructor

So, first case will be initialize the variable sample_attribute in 4th step, second will initialize the variable sample_attribute in 5th step. It's all depends on your requirement.

If you want to access any of the variables from Constructor, you need to use 1st case.

When you initialize your fields with information which gets passed into the constructor, you have no other choice but to initialize in the constructor. Otherwise, I prefer initialization on the spot as it saves me lines of code I have to read later.

These two versions are equivalent. But if new Sample() threw a checked exception you wouldn't be able to initialize it at field declaration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!