Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 218
Saurabh Gokhale Avatar asked Aug 26 '14 10:08

Saurabh Gokhale


People also ask

Can final class have non final methods?

All methods in a final class are implicitly final. To be pedantic, whether or not the methods are implicitly final is moot; there is no opportunity to attempt to override them!

What is the difference between a final class and a final method?

If we initialize a variable with the final keyword, then we cannot modify its value. If we declare a method as final, then it cannot be overridden by any subclasses. And, if we declare a class as final, we restrict the other classes to inherit or extend it.

What are the non final methods in Java?

If a constructor calls a method that is overridden in a subclass, it can cause the overriding method in the subclass to be called before the subclass has been initialized. This can lead to unexpected results.


1 Answers

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.

like image 146
Adam Siemion Avatar answered Nov 13 '22 12:11

Adam Siemion