In Java, is there a legitimate reason to call a non-final method from a class constructor?

前端 未结 5 634
北荒
北荒 2020-12-03 14:56

I recently spent quite a few minutes debugging a problem in production code that in the end turned out to be caused by a class calling an abstract method in its constructor,

5条回答
  •  生来不讨喜
    2020-12-03 15:26

    There are times it can be very hard not to.

    Take Joda Time, for example. Its Chronology type hierarchy is very deep, but the abstract AssembledChronology class is based on the idea that you assemble a bunch of "fields" (month-of-year etc). There's a non-final method, assembleFields, which is called during the constructor, in order to assemble the fields for that instance.

    They can't be passed up the constructor chain, because some of the fields need to refer back to the chronology which creates them, later on - and you can't use this in a chained constructor argument.

    I've gone to nasty lengths in Noda Time to avoid it actually being a virtual method call - but it's something remarkably similar, to be honest.

    It's a good idea to avoid this sort of thing if you possibly can... but sometimes it's a real pain in the neck to do so, especially if you want your type to be immutable after construction.

提交回复
热议问题