~ Java ~ deep understanding of final keyword

Posted by waverider303 on Tue, 01 Mar 2022 17:44:44 +0100

catalogue

final data

final method

final and private keywords

final class

In Java, final usually means "this cannot be changed". The reason for using final may be: design and efficiency. Learn about the final keyword from three possible situations: data, methods, and classes.

final data

In Java, data such as compile time constants must be basic data types and represented by the keyword final. Such constants must be assigned when they are defined.

A domain that is both static and final only occupies a storage space that cannot be changed.

For basic data types, final keeps the value constant; For the reference of an object, final makes the reference constant. Once a reference is initialized to point to an object, it cannot be changed to point to another object, but the object itself can be changed.

Understand final and static final through the following code:

import java.util.Random;

public class FinalData {
    private static Random rand = new Random(47);
    private String id;

    public FinalData(String id) {
        this.id = id;
    }
    private final int i = rand.nextInt(20);
    private static final int Value = rand.nextInt(20);

    @Override
    public String toString() {
        return  id + ": " +
                "i= " + i +
                " Value: " + Value;
    }

    public static void main(String[] args) {
        FinalData fd1 = new FinalData("fd1");
        System.out.println(fd1);
        //fd1.i = 5;Error: when the data is defined as final, it cannot be changed
        System.out.println("Create a new FinalData object");
        FinalData fd2 = new FinalData("fd2");
        System.out.println(fd2);
    }
}

The operation results are as follows: 

In the above code, i is defined with final and Value is defined with static final. In order to understand their meaning more clearly, the method of random generation is used during initialization. Through the operation results, it can be seen that:

① Final makes the data a constant and cannot be changed in the reference of the object, but the value of i will change when creating a new object, indicating that final can only make the defined variables unique in the reference of the object;

② Value will not change whether it is in the reference of the object or when creating a new object, because it is defined by static and has been initialized when loading, rather than when creating a new object.

final parameter

Java allows parameters to be declared as final in the parameter list. This means that the object pointed to by the parameter reference cannot be changed in the method.

For example:

    public int g(final int i){
        return i + 1;
    }

final method

There are two reasons for using the final method: ① lock the method to prevent any inherited class from modifying its meaning; ② In order to improve efficiency.

final and private keywords

All private methods in the class are implicitly specified as final. Since the private method cannot be used, it cannot be overwritten (its meaning can be modified). You can use the final modifier on the private method, but this does not add any additional meaning to the method.

Understand the final method through the following code:

 

class WithFinal{
    private final void f(){
        System.out.println("WithFinal.f()");
    }
    private void g(){
        System.out.println("WithFinal.g()");
    }
}
class FinalInit extends WithFinal {
    private final void f(){
        System.out.println("FinalInit.f()");
    }
    private void g(){
        System.out.println("FinalInit.g()");
    }
}
class FinalInit1 extends FinalInit{
    public final void f(){
        System.out.println("FinalInit.f()");
    }
    public void g(){
        System.out.println("FinalInit.g()");
    }
}
public class Final extends FinalInit{
    public static void main(String[] args) {
        FinalInit1 op1 = new FinalInit1();
        op1.f();
        op1.g();
        //Upward transformation can occur
        FinalInit op = op1;
        //But the finalininit method cannot be called
        //op.g();  Error: the method in finalinit is decorated with private
        //op.f();  Error: the method in finalinit is decorated with private
        WithFinal wp = new WithFinal();
        //wp. g();  Error: the method in withfinal is decorated with private
        //wp. f();  Error: the method in withfinal is decorated with private
    }
}

It can be seen from the above code that when a method is defined in private, it is not part of the interface of the base class. It is only some code hidden in the class, but has the same name. However, if a public, protected or package access method is generated with the same name in the exported class, the method will not produce the situation of "only with the same name" in the base class. At this point, the method is not overwritten, but a new method with the same name is generated.

Because the private method cannot be touched and can be effectively hidden, we don't need to think too much about it. We just regard it as existing because of the organizational structure of the class it belongs to.

final class

When the overall definition of a class is final, it means that the class can never be inherited.

Definition method:

final class Test{
    int i = 7;
    int j = 1;
}

In the process of writing code, you can choose whether to define this class as final class according to your own wishes. Because the final class prohibits inheritance, all methods in the final class are implicitly defined as final because they cannot be overridden. In the final class, you can add a final modifier to a method, but it doesn't make any sense.

 

Topics: Java Back-end