Search code examples
javastringimmutabilityfinal

final String class vs final methods of Non-final String class


I know that java.lang.String class is declared as final for security and performance related reasons.

What I'm not understanding is the part that whether same purpose could be achieved using all final variables and final methods instead of declaring final class ?

In short, what is the difference between below two code snippets .. e.g

public class final String { .. } 

v/s

// non final class
public class String {

// all final variables
private final char[] value;

// all final methods
public final String subString() { .. }
public final int length() { return value.length;}

// etc
}

EDITS

In simple words, can I achieve the same level of immutability by going with either approach ? Are they both good to make objects immutable ?


Solution

  • Final classes cannot be extended.

    Non final classes with final methods, can be extended (new methods can be added in subclasses) but the the existing final methods cannot be overridden.