immutable class should be final?

后端 未结 6 691
温柔的废话
温柔的废话 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:45

    Its a good idea to make a class immutable for performance reasons too. Take Integer.valueOf for example. When you call this static method it does not have to return a new Integer instance. It can return a previously created instance safe in the knowledge that when it passed you a reference to that instance last time you didn't modify it (I guess this is also good reasoning from a security reason perspective too).

    I agree with the standpoint taken in Effective Java on these matters -that you should either design your classes for extensibility or make them non-extensible. If its your intention to make something extensible perhaps consider an interface or abstract class.

    Also, you don't have to make the class final. You can make the constructors private.

提交回复
热议问题