Initialize class fields in constructor or at declaration?

前端 未结 15 2418
南旧
南旧 2020-11-22 01:16

I\'ve been programming in C# and Java recently and I am curious where the best place is to initialize my class fields.

Should I do it at declaration?:



        
15条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 01:58

    When you don't need some logic or error handling:

    • Initialize class fields at declaration

    When you need some logic or error handling:

    • Initialize class fields in constructor

    This works well when the initialization value is available and the initialization can be put on one line. However, this form of initialization has limitations because of its simplicity. If initialization requires some logic (for example, error handling or a for loop to fill a complex array), simple assignment is inadequate. Instance variables can be initialized in constructors, where error handling or other logic can be used.

    From https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html .

提交回复
热议问题