JavaRush /Java Blog /Random EN /Cheat sheet "Using the final keyword"
Level 10

Cheat sheet "Using the final keyword"

Published in the Random EN group
This article provides the basic uses of the final keyword in Java programming. Brief, clear descriptions of the application situation will help you quickly learn the material. The final keyword has different interpretations depending on where in the program it is used. But the essence of this word is the same - a ban on change . In fact, by applying this word to one of the essences of the Java language: a variable, object, method or class, we make it a constant, a stable and unchangeable value, like singer Joseph Kobzon’s hairstyle... Let me remind you of a brief definition of a constant. Constant is a constant quantity (scalar or vector) in mathematics, physics, chemistry. A mathematical constant is a quantity whose value does not change; in this it is the opposite of a variable. Let's look at 4 cases where we can use the word final .

1. Creating a constant of a primitive data type.

Here the MY_CONST value cannot be changed. Thus, if you write the word final next to a primitive variable, then it is a constant.
public class MyClass{
	public final int MY_CONST = 13;

2. Creating a reference type constant.

This code will not cause an error, but only until you assign a new value to the s1 variable . That is, the word final for reference types prohibits modification of the reference, not the object to which the reference points. It is also worth noting that assignment is valid anywhere in the program, but only once.
public class MyClass2{
	public final String s1;
	public MyClass2() {
		s1 = new String();

3. Prohibition on overriding a method in a descendant class

The word final next to a method prohibits overriding this method in descendant classes.
public class Example{
	public final void hello() {
	System.out.println(Hello my people!);
That is, if you create a class that inherits from Example and write the following code in it, an error will occur:
public class ExtendedExample extends Example{
	public void hello() {
		System.out.println("Extended hello everyone!!!");

4. Prohibition of creating a descendant class

A final class is a class that cannot be a superclass, that is, it is prohibited to write descendants for it.
public final class MyClass3 {

Author: Irina Volgina