JavaRush/Java Blog/Random EN/Final, Constants and Immutable in Java

Final, Constants and Immutable in Java

Published in the Random EN group
members
Hello! The word “modifier” is already familiar to you. At a minimum, you have come across access modifiers (public, private) and the static modifier. Today we’ll talk about the special final modifier . It can be said to “cement” those areas of our program where we need constant, unambiguous, unchanging behavior. It can be used in three areas of our program: classes, methods and variables. Immutable in Java: final, constants and Immutable - 2 Let's go through them one by one. If a class declaration contains the final modifier , this means that you cannot inherit from this class. In previous lectures, we saw a simple example of inheritance: we had a parent class Animal, and two child classes - CatandDog
public class Animal {
}

public class Cat extends Animal {
   //..поля и методы класса Cat
}

public class Dog extends Animal {

   //..поля и методы класса Dog
}
However, if we specify Animala modifier for a class final, classes will not be able to inherit from it Cateither Dog.
public final class Animal {

}

public class Cat extends Animal {

   //ошибка! Cannot inherit from final Animal
}
The compiler immediately produces an error. There are many -classes already implemented in Java final. The most famous of those that you constantly use is String. Additionally, if a class is declared as final, all its methods also become final. What does it mean? If a modifier is specified for a method final, this method cannot be overridden. For example, we have a class Animalthat defines a method voice(). However, dogs and cats clearly “talk” differently. Therefore, in each of the classes - Catand Dog- we will create a method voice(), but we will implement it differently.
public class Animal {

   public void voice() {
       System.out.println("Voice!");
   }
}

public class Cat extends Animal {

   @Override
   public void voice() {
       System.out.println("Meow!");
   }
}

public class Dog extends Animal {

   @Override
   public void voice() {
       System.out.println("Woof!");
   }
}
In classes Catand Dogwe have overridden the method of the parent class. Now the animal will vocalize depending on what class object it is:
public class Main {

   public static void main(String[] args) {

       Cat cat = new Cat();
       Dog dog = new Dog();

       cat.voice();
       dog.voice();
   }
}
Conclusion: Meow! Woof! However, if Animalwe declare a method in a class voice()as final, it will not be possible to redefine it in other classes:
public class Animal {

   public final void voice() {
       System.out.println("Voice!");
   }
}


public class Cat extends Animal {

   @Override
   public void voice() {//ошибка! final-метод не может быть переопределен!
       System.out.println("Meow!");
   }
}
Then our objects will be forced to use the method voice()as it is defined in the parent class:
public static void main(String[] args) {

   Cat cat = new Cat();
   Dog dog = new Dog();

   cat.voice();
   dog.voice();
}
Conclusion: Voice! Voice! Now about finalthe -variables. Otherwise they are called constants . First (and most importantly), the first value assigned to a constant cannot be changed. It is assigned once and forever.
public class Main {

   private static final int CONSTANT_EXAMPLE = 333;

   public static void main(String[] args) {

       CONSTANT_EXAMPLE = 999;//ошибка! Нельзя присвоить новое meaning final-переменной!
   }
}
The constant does not need to be initialized immediately. This can be done later. But the value assigned first will remain forever.
public static void main(String[] args) {

   final int CONSTANT_EXAMPLE;

   CONSTANT_EXAMPLE = 999;//так делать можно
}
Secondly, pay attention to the name of our variable. Java constants have a different naming convention. This is not the camelCase we are used to. In the case of a regular variable, we would call it constantExample, but the names of the constants are written in caps, and between the words (if there are several of them) there is an underscore - “CONSTANT_EXAMPLE”. Why are constants needed? For example, they will come in handy if you constantly use some constant value in a program. Let's say you decided to go down in history and write the game “The Witcher 4” alone. The game will obviously constantly use the name of the main character - “Geralt of Rivia”. It’s better to separate this line and the names of other heroes into a constant: the value you need will be stored in one place, and you definitely won’t make a mistake when typing it for the millionth time.
public class TheWitcher4 {

   private static final String GERALT_NAME = "Геральт из Ривии";
   private static final String YENNEFER_NAME = "Йеннифэр из Венгерберга";
   private static final String TRISS_NAME = "Трисс Меригольд";

   public static void main(String[] args) {

       System.out.println("Ведьмак 4");
       System.out.println("Это уже четвертая часть Ведьмака, а " + GERALT_NAME + " ниHow не определится кто ему" +
               " нравится больше: " + YENNEFER_NAME + " or " + TRISS_NAME);

       System.out.println("Но если вы никогда не играли в Ведьмака - начнем сначала.");
       System.out.println("Главного героя зовут " + GERALT_NAME);
       System.out.println(GERALT_NAME + " - ведьмак, охотник на чудовищ");
   }
}
Conclusion:
Ведьмак 4
Это уже четвертая часть Ведьмака, а Геральт из Ривии ниHow не определится, кто ему нравится больше: Йеннифэр из Венгерберга or Трисс Меригольд.
Но если вы никогда не играли в Ведьмака — начнем сначала.
Главного героя зовут Геральт из Ривии
Геральт из Ривии — ведьмак, охотник на чудовищ
We have separated the names of the characters into constants, and now we will definitely not misspell them, and there will be no need to write them by hand every time. Another plus: if we eventually need to change the value of a variable throughout the entire program, it’s enough to do it in one place, rather than manually redoing it throughout the entire code :)

Immutable types

During your time working in Java, you are probably already accustomed to the fact that the programmer almost completely controls the state of all objects. Wanted - created an object Cat. If I wanted to, I renamed it. If he wanted, he changed his age, or something else. But in Java there are several data types that have a special state. They are immutable , or Immutable . This means that if a class is immutable, the state of its objects cannot be changed. Examples? You might be surprised, but the most famous example of the Immutable class is String! It would seem that we can’t change the value of a string? Let's try:
public static void main(String[] args) {

   String str1 = "I love Java";

   String str2 = str1;//обе переменные-ссылки указывают на одну строку.
   System.out.println(str2);

   str1 = "I love Python";//но поведение str1 ниHow не влияет на str2
   System.out.println(str2);//str2 продолжает указывать на строку "I love Java", хотя str1 уже указывает на другой an object
}
Conclusion: I love Java I love Java After we wrote:
str1 = "I love Python";
the object with the string "I love Java" has not changed and has not gone anywhere. It exists safely and has exactly the same text inside it as before. Code:
str1 = "I love Python";
just created another object and now the variable str1points to it. But we cannot influence the “I love Java” object in any way. Okay, let's try it differently! The class Stringis full of methods, and some of them seem to change the state of the row! For example, there is a method replace(). Let's change the word “Java” to the word “Python” in our line!
public static void main(String[] args) {

   String str1 = "I love Java";

   String str2 = str1;//обе переменные-ссылки указывают на одну строку.
   System.out.println(str2);

   str1.replace("Java", "Python");//попробуем изменить состояние str1, заменив слово "Java" на “Python”
   System.out.println(str2);
}
Conclusion: I love Java I love Java It didn’t work out again! Maybe the curve method doesn't work? Let's try another one. For example, substring(). Trims a string based on the numbers of the transmitted characters. Let's trim ours to the first 10 characters:
public static void main(String[] args) {

   String str1 = "I love Java";

   String str2 = str1;//обе переменные-ссылки указывают на одну строку.
   System.out.println(str2);

   str1.substring(10);//обрезаем исходную строку
   System.out.println(str2);
}
Conclusion: I love Java I love Java Immutable in Java: final, constants and Immutable - 3 Nothing has changed. And it shouldn't have. As we said, objects Stringare immutable. What then are all these class methods String? They can trim the line, change the characters in it, etc. Why are they needed then if nothing happens? They can! But they return a new string object each time. It's no use writing:
str1.replace("Java", "Python");
- you will not change the original object. But if you write the result of the method into a new reference variable, you will immediately see the difference!
public static void main(String[] args) {

   String str1 = "I love Java";

   String str2 = str1;//обе переменные-ссылки указывают на одну строку.
   System.out.println(str2);

   String str1AfterReplacement =  str1.replace("Java", "Python");
   System.out.println(str2);

   System.out.println(str1AfterReplacement);
}
This is the only way all these methods Stringwork. You can't do anything with the "I love Java" object. Just create a new object and write: “New object = the result of some manipulations with the “I love Java” object .” What other types are Immutable? From what you definitely need to remember now - all wrapper classes over primitive types are immutable. Integer, Byte, Character, Short, Boolean, Long, Double, Float- all these classes create Immutable objects. This also includes classes used to create large numbers - BigIntegerand BigDecimal. We recently went through exceptions and touched upon StackTrace. So: objects of the java.lang.StackTraceElement class are also immutable. This is logical: if someone could change the data on our stack, it could negate all work with it. Imagine someone goes into StackTrace and changes OutOfMemoryError to FileNotFoundException . And you should work with this stack and look for the cause of the error. And the program does not use files at all :) Therefore, to be on the safe side, these objects were made immutable. Well, with StackTraceElement it’s more or less clear. Why would anyone want to make strings immutable? What would be the problem if it were possible to change their values. It would probably be even more convenient :/ There are several reasons for this. Firstly, saving memory. Immutable strings can be placed in String Pooland the same ones can be used each time instead of creating new ones. Secondly, safety. For example, most logins and passwords in any program are strings. The possibility of changing them could lead to problems with authorization. There are other reasons, but we haven’t gotten to them yet in learning Java—we’ll come back later.
Comments
  • Popular
  • New
  • Old
You must be signed in to leave a comment
This page doesn't have any comments yet