Why final keyword is necessary for immutable class?

后端 未结 7 1222
陌清茗
陌清茗 2020-12-08 01:17

Could you please clarify that why final keyword is required before class when we are making it an immutable one. I mean, if we declare all of it\'s attr

7条回答
  •  [愿得一人]
    2020-12-08 02:06

    If all public and protected methods are final and none of them allows modifying private fields, and all public and protected fields are both final and immutable, then I guess it could be said class is semi-immutable, or sort of constant.

    But things break down when you create a subclass and need to override equals and hashcode. And can not because you made them final... So the whole thing is broken, so just make the whole class final to prevent programmer from being a fool by accident.

    As an alternative to doing this kind of bastardized version immutability, you have several options.

    If you want to attach extra data to immutable instance, use Map. Like if you wanted to add age to name, you would not do class NameAge extends String... :-)

    If you want to add methods, create a class of static utility functions. That is a bit klunky, but it is the current Java way, Apache commons for example is full of such classes.

    If you want to add extra methods and data, create a wrapper class with delegate methods to methods of the immutable class. Anybody needing to use the extra methods needs to be aware of them anyway, and there is not much practical difference in casting to derived non-immutable class or doing something like new MyWrapper(myImmutableObj) for many use cases.

    When you really have to have reference to original imutable object (like storing it in existing class you can not change), but need the extra data somewhere, you need to use the Map approach to keep the extra data around, or something like that.

提交回复
热议问题