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 redundant?
final String s = "Hello World"
same as
String s = "Hello World"
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 redundant?
final String s = "Hello World"
same as
String s = "Hello World"
When you use
final
on the variable, it means that it cannot be re-assigned. Consider the following example:If you try to run it, you will get an error on
a=b
:Now, I think you were wondering whether it matters to have a
final
or not in front of theString
data type specifically. Although you may have heard thatString
is immutable, you can still re-assign something likeString s = "Hello World!";
to another string value. This distinction is due to the fact that you are actually re-assigning the reference ofString s
to a new string. Therefore, the following is valid:But you can use the
final
declaration to prevent this change:The
final
declaration is great to use if you want to ensure that no one can change yourString
reference. You can usefinal
for other data types as well to prevent the reference from being changed.final
on a variable has nothing to do with whether the class isfinal
.A final variable cannot be bound to another instance, so this is not valid:
A final class cannot be extended
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.)