I came across this question when I was studying immutability in java. It is said that in order to make a class immutable , the class should be declared final so that it's methods can not be extended. I have a question such that, I could achieve the same if I mark the methods private or methods final in java. If I do so I don't have to mark the class as final. I am getting this correct. Your thoughts on this highly appreciated.
-
the question itself explaing what is targetted is *in order to make a class immutable* and not make methods not to be overriden. – Naman Sep 20 '17 at 06:40
-
what if you add new method and fields in sub class @kltis – VedantK Sep 20 '17 at 06:50
3 Answers
A final
class in Java cannot be subclassed. This means that, by definition, its methods cannot be overloaded, nor new methods (behaviors) added to the class. On the other hand, if you were to mark all the methods of a class final
then it means something different. A final
method cannot be overriden or hidden. However, marking all methods final
alone would still allow the class to be subclassed and new methods/behaviors added to it.

- 502,043
- 27
- 286
- 360
Allowing to override an immutable class also allows to add mutable data.
class SuddenlyMutableString extends String {
private int id;
public int getId() { return id; }
public void setId(int i) { id = i; }
}
So while setting your methods to final
may prevent mutability of the existing data, you may still get mutable subclasses.

- 14,137
- 4
- 32
- 53
The thing with a non-final class with no public mutating methods or fields is that you can still subclass it.
Say you have this immutable class:
class Point {
private int x, y;
// getters
// constructors
}
This class has no public mutating methods or fields, but it is not final, so other people can still subclass it to make it mutable:
class MyPoint extends Point {
public int foo;
}
Now suddenly you can change foo
's value however you want. MyPoint
now becomes mutable!
This is why you should mark immutable classes as final.

- 213,210
- 22
- 193
- 313
-
or making its constructor private and return from factory method inside parent class. – amarnath harish Sep 08 '18 at 17:38