Week 13 — What is the purpose of the final keyword?
Question of the Week #13
What is the purpose of the final keyword?
24 Replies
The final keyword is used to declare that a variable cannot be changed later in the program. For example: means that the int doge cannot be changed later in the program (aka the variable is a constant).
Submission from Dogepressed#1205
The final keyword has 3 types it can be used on. Data, Methods, and Classes. We'll review the different use cases and the impact.
Data
For Data it breaks into three different use cases.
- Limiting the scope of Object Assignment.
The field
private final Object myObject
can only be assigned once in the scope of the constructor. If you try to reassign the reference to a new object outside of the constructor, you'll get a build error, or if you try multiple assignments in the Constructor scope you'll also get a build error.
Note that private final Object
only creates an immutable reference to the object, if all the inner fields aren't final you can still get a mutable object. This usage of final
is nice for enforcing a more functional design, since you can create Objects with immutable states.
- Creating local constants.
Where private final Object myObject
creates an immutable reference, private final <Primitive> myPrimitive
creates locally scoped constants. This can be combined with private final Object myObject
to create completely immutable data.
- Creating global constants.
public static final <Object/Primitive> myThing = <Value>
creates a globally scoped reference. This concept has been used for something like a global String bank, (Not to be confused with Java's Actual String bank), referencing Math Constants, Referencing Default Configuration, etc. The nice this is that in combination with final
, we can use static
with less fear about any concurrency issues.
Methods/Classes
final
in this context means the method/class cannot be Overriden. Given how Java leads itself to OOP, this can be a useful method to make sure that certain aspects of a contract are upheld. For example you might have a business logic class with the following.
```java
public class MyActionServiceextends AbstractActionService {
public MyActionService() {
this.myActionName = "Custom Action";
}
public abstract class AbstractActionService {
private final String myActionName;
public void doAction();
public final void logAction() {
log.info(myActionName + " was taken at " + Instance.now());
}
}
}
```
Now we can have a class extend our class, but not override our logAction, which can have a strict contract for the format.
For classes this keyword means that the class can't be extended. This feature is useful for when library developers want to prevent extension of their classes.
⭐ Submission from LeanusCrain#5877
A final keyword declares the method can not be overridden in any sub class where the method is referenced
final int age = 12
Submission from Prinzessin#0001
final = once the variable is assigned, it cannot be assigned again
Submission from toastmush#5955
The final keyword does not allow whatever is being created to have its value changed
Example 1: A final variable:
Example 2: A final method:
Example 3: A final class:
Submission from amicharski#7113
The
final
keyword is used when you declare a variable. It is used to make the variable value unchangeable. For all primitive types, the value will never be changed. For objects such as Lists, Arrays, Maps, and similar objects, you will not be able to create a new object, but you will still be able to modify the contents of that object.
Submission from MinecraftMan1013#7242
the keyword 'final' is used to declare a variable, method or class that cannot be modified or extended.
Submission from pwrpl3#8029
The final keyword makes a variable read only. When a field has the final modifier, only the constructor or static constructor can set it, once. No more modifications are allowed. The same happens with a local with the final modifier, it can only be set once.
Submission from 0x150#9699
When marking a variable with
final
, it cannot be reassigned.
For reference variables (objects), it is possible to change the content of the referenced objects but it is not possible to reassign the variable
This behaviour is the similar with fields.
final
fields need to be initialized in the declaration, initializer blocks or in the constructor.
The
final
keyword can also be used on classes. If a class is marked with final
, it is not possible to create subclasses of the said class:
A class is called "immutable", if all its fields are marked with final
and the class itself is final
.
If a class is immutable, its fields can never change their associated values.
Records are implicitly immutable.
⭐ Submission from dan1st#7327
The
final
keyword is used to make variables or whatever only able to be assigned once, when its assigned it cannot be reassigned.
trying to reassign a final variable results in an exception being thrown to your doorstep.
final
variables need to be initialized at either the same line its being created in a constructor from the same class the variable is in or in a "instance initializer block".
Constructor example:
Instance Initializer example:
Submission from Aussied#7593
to make sure that a variable can not be edited for example:
would be invalid
Submission from AmyDon#1791
The purpose of the final keyword is, to mark a variable as a constant variable, which should not be changed later in the code.
Here an example:
Here you have a class and a function where you add the Author to a quote. You want the Author to always be yourself in this example, so you added the name in the constructor.
Instead of creating a variable and setting the name of the author, you could simply change the variable to be a final string like this:
Therefore, use a final variable, if you want to use the same value the whole time instead of creating a normal attribute and setting it once, to not accidentally change the value.
Submission from Giotsche#5027
In Java, the
final
keyword can be used in several contexts to indicate that a variable, method, or class cannot be changed after it has been initialized or defined.
1. Variable: When a variable is declared as final
, its value cannot be changed once it is assigned.
2. Method: When a method is declared as final
, it cannot be overridden by any subclass.
3. Class: When a class is declared as final
, it cannot be extended by any subclass.
The purpose of using final
keyword is to ensure that the value or behavior of a variable, method, or class remains constant throughout the program, which can prevent bugs and make the code more readable and maintainable. It also provides a way to enforce immutability, which can help in multithreaded environments.Here are some examples of using the
final
keyword in Java:
1. Variable:
2. Method:
3. Class:
⭐ Submission from LynnCodes#2568
The final keyword basically means that the thing is final, depending on the context. One of the most known usage of the keyword is in variables. If the keyword is present after the variable visibility it means that this variable's value is constant and will remain like this, even reflections won't be able to modify it. On classes, final variable must be initialized, the code will not compile if your class will initialize without the variable with it. The following is an example for classes:
The keyword can also be used on classes themselves, and on methods. On Classes it means that the class is not extendable, and on methods it means that it is not overridable. This is how final is used on them:
Note There is no point of using a final method inside a final class, as you cannot extend the class anyway, which is required to override it's methods, this was just an example.
⭐ Submission from BlueTree242#9734
Final keyword is a keyword which can be used to make a variable constant, meaning you can assign its value at the time of initialization but you cannot assign any value to it after initialization, example:
Non-final variable
Final variable
Submission from Rudiemc#4088
The final keyword in Java indicates that the variable cannot be changed. These variables cannot be inherited either.
Submission from Maruvert#2038
The final keyword is a non-access modifier used for classes, methods and variabes alike that prevent them from being changed lateron in our code.
Submission from mayokun#5069
In Java, the final keyword is a non-access modifier. It can be used with variables, methods, and classes. Once any variable, method or class is declared final, it can be assigned only once. So the final variable can't be reinitialized with another value.
Submission from protozoid#5861
The final keyword ensures that values, methods, or classes remain unchanged after initialization, providing a level of safety and predictability in the program.
So here's an example:
Here, the variable PI is declared as final, which means that its value cannot be changed after initialization.
Submission from DTechish#5832