Rajinder Menu

Why String is declared final?


String class is made final to close one of the open doors which can make an immutable class mutable.

There are many chances by which an immutable class can be made mutable if it is allowed to be subclassed (i.e if it can be extended). Therefore often immutable classes are made final so that they cannot be extended, making them strongly immutbale as against to weakly immutable.

Thus String is made final to make it strongly immutable.

If String had not been made final, then one can create its subclass and :

1)Can add new fields in sublcass which are not declared final (mutable):

New fields can be added to subclass of String class without declaring them final. So object of this subclass would not be immutable.

Now object of subclass of String class would also be object of  String class. This would cause an object of String class to exist which is not immutable.

2) Can override existing methods:

A subclass can override existing methods of String class which can then return different values each time they are called, thus breaking immutabillty. Example,

one can override public charAt(int index) method of String class to return some random character each time it is called as:

@Override
public char charAt(int index){
//retruning some randomly selected character.
}

thus breaking the immutablilty and whole design of String class as many features of String class depends on its immutabilty.





I would like to know your comments and if you liked the article then please share it on social networking buttons.


3 comments:

  1. Thank you it was nice explanation of why String is final.

    ReplyDelete
  2. Thanks!
    It's first good explanation about "final", not about immutable in general!

    ReplyDelete
  3. Thanks a lot! It's first normal explanation about exactly "final" keyword.

    ReplyDelete