If a class is defined as final
and we declare an instance of the final class... Would it make any difference? or is final
in such cases would be re
final
on a variable has nothing to do with whether the class is final
.
final String s = "Hello World";
s = "Goodbye"; // illegal
String s2 = "Hello World";
s2 = "Goodbye"; // legal
A final variable cannot be bound to another instance, so this is not valid:
final String s = "123";
s = "234"; // doesn't work!
A final class cannot be extended
final class A {
}
class B extends A { // does not work!
}
And both of this is not to be confused with immutable classes (like String
). Instances of immutable classes won't change their state. (There is no direct language support for immutable classes, but in practice most of the time all attributes of immutable classes are declared final.)
When you use final
on the variable, it means that it cannot be re-assigned. Consider the following example:
public class FinalExample {
private final String a = "Hello World!"; // cannot be reassigned
private String b = "Goodbye World!"; // can be reassigned
public FinalExample() {
a = b; // ILLEGAL: this field cannot be re-assigned
b = a;
}
public static void main(String[] args) {
new FinalExample();
}
}
If you try to run it, you will get an error on a=b
:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The final field FinalExample.a cannot be assigned
at FinalExample.<init>(FinalExample.java:7)
at FinalExample.main(FinalExample.java:12)
Now, I think you were wondering whether it matters to have a final
or not in front of the String
data type specifically. Although you may have heard that String
is immutable, you can still re-assign something like String s = "Hello World!";
to another string value. This distinction is due to the fact that you are actually re-assigning the reference of String s
to a new string. Therefore, the following is valid:
String s = "Hello World";
s = "Goodbye World!";
System.out.println(s);
Output: Goodbye World!
But you can use the final
declaration to prevent this change:
final String s = "Hello World";
s = "Goodbye World!";
System.out.println(s);
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The final local variable s cannot be assigned. It must be blank and not using a compound assignment
The final
declaration is great to use if you want to ensure that no one can change your String
reference. You can use final
for other data types as well to prevent the reference from being changed.