Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

5
  • and how is this answering what i'm asking. Commented Nov 21, 2013 at 22:21
  • 2
    Well, you cited an excerpt of the documentation telling that immutable classes should be final. I'm explaining why. The documentation doesn't tell to make methods final. It's redundant to make them final if the class is final. So, if you're asking "why should I make methods final?", my answer is, as the documentation says: don't. Make your class final. Commented Nov 21, 2013 at 22:24
  • 2
    What you describe is commonly expressed wisdom, but I don't entirely agree with it. It's certainly true that a subclass of a class whose contract specifies that it is immutable might violate that contract, but the same would be true of any contract of any inheritable class. There are many situations where there's no logical reason for an immutable class to allow subclasses (though the same is true for all sorts of classes--not just immutable ones), but there are also many situations where subclassing would be reasonable and useful (for immutable classes as well as mutable ones). Commented Nov 21, 2013 at 22:28
  • @supercat: I'm not saying that all classes should be immutable. But if you want to use the tool that is immutability to make your concurrrent code rock solid and easier to understand and maintain, then you'd better make sure that the application doesn't fall apart because a developer created a mutable subclass without realizing the implications it might have. Commented Nov 21, 2013 at 22:33
  • 2
    @JBNizet: If there's no reason for an immutable class to allow subclassing, it's probably good to seal it. On the other hand, there are other situations where inheritance is appropriate, such as an ImmutableShape class. Inheritance and inheritability should be used where they make sense, and not where they don't, whether a class is mutable or not. Incidentally, I wish people would only use "immutable" when they really mean immutable, and "read-only" when they actually mean "read-only". They're fundamentally different concepts. Commented Nov 21, 2013 at 22:37