JAVA BASICS IN DETAIL
Java final keyword
final keyword ( final keyword) restricts later changes. For a variable it prevents reassignment, for a method it prevents overriding, and for a class it prevents inheritance.
Three main uses
| Where is it written? | What does it restrict? | What does it not do? |
|---|---|---|
| On a variable | The value or reference can be assigned only once | Does not always make the referenced object immutable |
| On a method | A subclass cannot override the method | Does not prevent inheritance or calls to the method |
| On a class | Another class cannot extend it using extends | Does not prevent creating instances of the class |
1. final variable is assigned once
Working example
final int MINIMALUS_AMZIUS = 18;
System.out.println(MINIMALUS_AMZIUS);18
- To the variable
MINIMALUS_AMZIUSwe first assign18. - This value can be read and used in calculations.
finaldoes not mean the value must be known at compile time: it simply must be assigned only once.
Non-compiling example
final int MINIMALUS_AMZIUS = 18;
MINIMALUS_AMZIUS = 21; // Error: a second assignment is not allowedThe code does not compile. The incorrect line remains active, and its trailing comment explains the reason: final variable has already been assigned a value.
A value can be assigned in the constructor
A class's final field can be declared without a value and assigned in each constructor. This is called a blank final field ( blank final field).
class Uzsakymas {
final int numeris;
String pirkejas;
Uzsakymas(int numeris, String pirkejas) {
this.numeris = numeris;
this.pirkejas = pirkejas;
}
}
Uzsakymas uzsakymas = new Uzsakymas(1042, "Ieva");
System.out.println(uzsakymas.numeris);
System.out.println(uzsakymas.pirkejas);1042
Ieva
Each Uzsakymas object can have a different number, but an existing object's number cannot be reassigned.
class Uzsakymas {
final int numeris;
Uzsakymas() {
// Error: numeris has not been assigned a value
}
}The code does not compile. Every constructor path must assign the final field exactly once.
final reference does not mean an immutable object
Working example: changing object contents
final StringBuilder tekstas = new StringBuilder("Pirkinių sąrašas");
tekstas.append(": duona, pienas");
System.out.println(tekstas);Pirkinių sąrašas: duona, pienas
finallocks the referencetekstasto oneStringBuilderobject.- The
StringBuilderitself is mutable, so its contents can be extended withappend().
Non-compiling example: redirecting a reference
final StringBuilder tekstas = new StringBuilder("Pirkinių sąrašas");
tekstas = new StringBuilder("Kitas sąrašas"); // Error: second assignmentThe code does not compile. Instead of changing the old object's state, the code tries to redirect the variable tekstas to a different object.
final reference and an immutable ( immutable) object are not the same. Immutability also requires appropriate class design.
static final – a shared class constant
class Laikas {
static final int MINUCIU_PER_VALANDA = 60;
static final int SEKUNDZIU_PER_MINUTE;
static {
SEKUNDZIU_PER_MINUTE = 60;
}
}
int sekundziu = 2
* Laikas.MINUCIU_PER_VALANDA
* Laikas.SEKUNDZIU_PER_MINUTE;
System.out.println(sekundziu);7200
staticmeans the entire class shares one value.finalprevents assigning it a second time.- The value can be assigned immediately or in a static initializer block.
- Constant names conventionally use
UPPER_SNAKE_CASEstyle.
final method parameters and local variables
Working example
class Pasisveikinimas {
static String sukurti(final String vardas) {
return "Labas, " + vardas + "!";
}
}
System.out.println(Pasisveikinimas.sukurti("Rūta"));Labas, Rūta!
final parameter cannot be reassigned inside the method. This can express the intention not to change it, but an object parameter's internal state can still change if its class allows it.
Non-compiling example
class Pasisveikinimas {
static String sukurti(final String vardas) {
vardas = "Kitas vardas"; // Error: a final parameter cannot be changed
return "Labas, " + vardas + "!";
}
}The code does not compile because the method tries to assign the parameter vardas a different string.
2. final method cannot be overridden
class Mokestis {
final double galutineKaina(double kaina) {
return kaina * 1.21;
}
}
class SpecialusMokestis extends Mokestis {
double galutineKaina(double kaina) { // Error: a final method cannot be overridden
return kaina;
}
}The code does not compile because galutineKaina(double) is marked final.
final method is used when subclasses must not change an important rule or algorithm. They still inherit and can call the method:
class Mokestis {
final double galutineKaina(double kaina) {
return kaina * 1.21;
}
}
class PvmMokestis extends Mokestis {
void rodyti(double kaina) {
System.out.println(galutineKaina(kaina));
}
}
PvmMokestis mokestis = new PvmMokestis();
mokestis.rodyti(100);121.0
3. final class cannot be extended
final class AsmensKodas {
private final String reiksme;
AsmensKodas(String reiksme) {
this.reiksme = reiksme;
}
String gauti() {
return reiksme;
}
}
class SpecialusKodas extends AsmensKodas { // Error: a final class cannot be extended
SpecialusKodas(String reiksme) {
super(reiksme);
}
}The code does not compile because SpecialusKodas tries to extend final class a AsmensKodas.
final class ends the inheritance chain. This is useful when subclassing cannot safely change its behavior or its immutability rules require a fully controlled structure.
String is final class. Another class cannot extend it and change string behavior.
What does final not guarantee?
finalreference does not guarantee an immutable object.finalclass alone does not guarantee immutability: its fields can still change.finaldoes not automatically make code thread-safe.finalis not an access modifier and does not determine who can see a member.finalandfinallyare different Java keywords with different purposes.
When should you use it?
| Situation | Solution |
|---|---|
| A value or reference must not change after assignment | final variable |
| A shared class constant | static final field |
| Subclasses may inherit the method but cannot change its rule | final method |
| A class must have no subclasses | final class |
| An object must be fully immutable | Using final alone is insufficient: an immutable class design is needed |
What should you remember?
finalallows a variable to be assigned only once.- A blank
finalfield must be initialized in every constructor. finalreference cannot point to another object, but the object itself can remain mutable.finalmethod cannot be overridden, but can be inherited and called.finalclass cannot be extended.static finalis most often used for shared class constants.