immutable class should be final?

后端 未结 6 717
温柔的废话
温柔的废话 2020-11-29 09:15

It says in this article that:

Making a class final because it is immutable is a good reason to do so.

I\'m a bit puzzled by thi

6条回答
  •  难免孤独
    2020-11-29 09:56

    Following the Liskov Substitution Principle a subclass can extend but never redefine the contract of its parent. If the base class is immutable then its hard to find examples of where its functionality could be usefully extended without breaking the contract.

    Note that it is possible in principle to extend an immutable class and change the base fields e.g. if the base class contains a reference to an array the elements within the array cannot be declared final. Obviously the semantics of methods can also be changed via overriding.

    I suppose you could declare all the fields as private and all the methods as final, but then what would be the use of inheriting?

提交回复
热议问题