последнее ключевое слово в java

Опубликовано: 15 Февраля, 2022

Ключевое слово final используется в разных контекстах. Прежде всего, final - это модификатор отсутствия доступа, применимый только к переменной, методу или классу. Далее следуют разные контексты, в которых используется final.

Конечные переменные

Когда переменная объявляется с ключевым словом final , ее значение не может быть изменено, по сути, это константа. Это также означает, что вы должны инициализировать конечную переменную. Если последняя переменная является ссылкой, это означает, что переменная не может быть повторно привязана для ссылки на другой объект, но внутреннее состояние объекта, на который указывает эта ссылочная переменная, может быть изменено, т.е. вы можете добавлять или удалять элементы из окончательного массива или окончательной коллекции. . Рекомендуется представлять переменные final в верхнем регистре, разделяя слова подчеркиванием.

Примеры :

// a final variable
final int THRESHOLD = 5;
// a blank final variable
final int THRESHOLD;
// a final static variable PI
static final double PI = 3.141592653589793;
// a  blank final static  variable
static final double PI;

Инициализация последней переменной:
Мы должны инициализировать конечную переменную, иначе компилятор выдаст ошибку времени компиляции. Конечная переменная может быть инициализирована только один раз, либо с помощью инициализатора, либо с помощью оператора присваивания. Есть три способа инициализировать конечную переменную:

  1. Вы можете инициализировать конечную переменную при ее объявлении. Этот подход является наиболее распространенным. Конечная переменная называется пустой конечной переменной , если она не инициализирована при объявлении. Ниже приведены два способа инициализировать пустую конечную переменную.
  2. Пустая конечная переменная может быть инициализирована внутри блока инициализатора экземпляра или внутри конструктора. Если у вас более одного конструктора в вашем классе, тогда он должен быть инициализирован во всех из них, иначе будет выдана ошибка времени компиляции.
  3. Пустая конечная статическая переменная может быть инициализирована внутри статического блока.

Let us see above different ways of initializing a final variable through an example.

//Java program to demonstrate different
// ways of initializing a final variable
  
class Gfg 
{
    // a final variable
    // direct initialize
    final int THRESHOLD = 5;
      
    // a blank final variable
    final int CAPACITY;
      
    // another blank final variable
    final int  MINIMUM;
      
    // a final static variable PI
    // direct initialize
    static final double PI = 3.141592653589793;
      
    // a  blank final static  variable
    static final double EULERCONSTANT;
      
    // instance initializer block for 
    // initializing CAPACITY
    {
        CAPACITY = 25;
    }
      
    // static initializer block for 
    // initializing EULERCONSTANT
    static{
        EULERCONSTANT = 2.3;
    }
      
    // constructor for initializing MINIMUM
    // Note that if there are more than one
    // constructor, you must initialize MINIMUM
    // in them also
    public GFG() 
    {
        MINIMUM = -1;
    }
          
}

Когда использовать конечную переменную:

Единственное различие между нормальной переменной и конечной переменной заключается в том, что мы можем повторно присвоить значение нормальной переменной, но мы не можем изменить значение конечной переменной после ее назначения. Следовательно, конечные переменные должны использоваться только для значений, которые мы хотим оставаться постоянными на протяжении всего выполнения программы.

Ссылка на конечную переменную:
Когда конечная переменная является ссылкой на объект, эта конечная переменная называется конечной ссылочной переменной. Например, последняя переменная StringBuffer выглядит так:

final StringBuffer sb;

As you know that a final variable cannot be re-assign. But in case of a reference final variable, internal state of the object pointed by that reference variable can be changed. Note that this is not re-assigning. This property of final is called non-transitivity. To understand what is mean by internal state of the object, see below example :

// Java program to demonstrate 
// reference final variable
  
class Gfg
{
    public static void main(String[] args) 
    {
        // a final reference variable sb
        final StringBuilder sb = new StringBuilder("Geeks");
          
        System.out.println(sb);
          
        // changing internal state of object
        // reference by final reference variable sb
        sb.append("ForGeeks");
          
        System.out.println(sb);
    }    
}

Выход:

Компьютерщики
GeeksForGeeks

Свойство нетранзитивности также применяется к массивам, потому что массивы являются объектами в java. Массивы с ключевым словом final также называются конечными массивами.

Note :

  1. As discussed above, a final variable cannot be reassign, doing it will throw compile-time error.
    // Java program to demonstrate re-assigning
    // final variable will throw compile-time error
      
    class Gfg 
    {
        static final int CAPACITY = 4;
          
        public static void main(String args[])
        {
            // re-assigning final variable
            // will throw compile-time error
            CAPACITY = 5;
        }
    }

    Output

    Compiler Error: cannot assign a value to final variable CAPACITY 
  2. When a final variable is created inside a method/constructor/block, it is called local final variable, and it must initialize once where it is created. See below program for local final variable
    // Java program to demonstrate
    // local final variable
      
    // The following program compiles and runs fine
      
    class Gfg
    {
        public static void main(String args[])
        {
            // local final variable
            final int i;
            i = 20
            System.out.println(i);
        }
    }

    Output:

    20
  3. Note the difference between C++ const variables and Java final variables. const variables in C++ must be assigned a value when declared. For final variables in Java, it is not necessary as we see in above examples. A final variable can be assigned value later, but only once.
  4. final with foreach loop : final with for-each statement is a legal statement.
    // Java program to demonstrate final
    // with for-each statement
      
    class Gfg 
    {
        public static void main(String[] args) 
        {
            int arr[] = {1, 2, 3};
              
            // final with for-each statement
            // legal statement
            for (final int i : arr)
                System.out.print(i + " ");
        }    
    }

    Output:

    1 2 3

    Explanation : Since the i variable goes out of scope with each iteration of the loop, it is actually re-declaration each iteration, allowing the same token (i.e. i) to be used to represent multiple variables.

Final classes

When a class is declared with final keyword, it is called a final class. A final class cannot be extended(inherited). There are two uses of a final class :

  1. One is definitely to prevent inheritance, as final classes cannot be extended. For example, all Wrapper Classes like Integer,Float etc. are final classes. We can not extend them.
    final class A
    {
         // methods and fields
    }
    // The following class is illegal.
    class B extends A 
    { 
        // COMPILE-ERROR! Can"t subclass A
    }
    
  2. The other use of final with classes is to create an immutable class like the predefined String class.You can not make a class immutable without making it final.

Final methods

When a method is declared with final keyword, it is called a final method. A final method cannot be overridden. The Object class does this—a number of its methods are final.We must declare methods with final keyword for which we required to follow the same implementation throughout all the derived classes. The following fragment illustrates final keyword with a method:

class A 
{
    final void m1() 
    {
        System.out.println("This is a final method.");
    }
}

class B extends A 
{
    void m1()
    { 
        // COMPILE-ERROR! Can"t override.
        System.out.println("Illegal!");
    }
}

For more examples and behavior of final methods and final classes, please see Using final with inheritance

final vs abstract

Please see abstract in java article for differences between final and abstract.
Related Interview Question(Important) : Difference between final, finally and finalize in Java

This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.