Friday, July 22, 2016

Can we create a immutable class without marking it as final?

Most of java developers (may be 90%) will answer this question with a big "NOooo" and its absolutely fine to answer with a big "NOooo" because its written everywhere on internet that for a class to be immutable it must be final but surprisingly we can create a immutable class without declaring it as final.

So the answer of the above question is "YES" we can create a immutable class without making it as final but how???

Let me tell you one of such example from java classes itself  "BigInteger" class is immutable but its not final



As marked in red BigInteger is not a final class.

Let's test BigInteger's immutability now

Since BigInteger is immutable therefore the output of the above program will be 0.

Actually Immutability is a concept according to which ones the object created then it can not be modified.

Let's think from JVM point of view, from JVM point of view all threads must share the same copy of the object and it is fully constructed before any thread accesses it and the state of the object doesn't change after its construction.

Immutability means there is no way yo change the state of the object once it is created and this is achieved by three thumb rules which makes the compiler to recognize that class is immutable and they are as follows :-

  • all non private fields should be final
  • make sure there is no method in the class that can change the fields of the object either directly or indirectly
  • any object reference defined in the class can't be modified outside from the class

Therefore for creating immutable class it is not mandatory to mark the class as final.

No comments:

Post a Comment