Search code examples
javaimmutabilityfinalprotectedaccess-modifiers

Java : private method vs final class


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.


Solution

  • 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.