Java learning keywords final

The final keyword can be mainly used for variable declaration, final method and final class, which are introduced one by one below.

final variable

For the variable defined by final, once it is set, the value of the variable cannot be changed. At the same time, it must be assigned an assignment when it is declared (in some cases, assignment can be done after declaration, but in order to cultivate good programming habits, when declaring assignment is best).

Final can modify general constants, as well as object references. Since arrays can also be referred to as objects, final can also modify arrays. The following is an intuitive explanation through the code:

class Yun{
    final double PI;
    public Yun(){
        //这个函数会被报错,原因是没有给PI进行初始化
    }
    public Yun(double pi){
        this.PI=pi;
    }
    /*public void setPi(double pi){
        this.PI=pi;   //这个函数是不被允许的,因为不能对final进行二次修改
    }*/
    public double GetPi(){
        return PI;
    }
}
public class Demo {
    public static void main(String[] args) {
        Yun y=new Yun(1);       //调用含参构造函数,进行初始化
        final double pi;        //final定义的变量,申明时并未对其进行初始化
        pi=3.14;
        System.out.println("这是我定义的变量pi:"+pi);
        System.out.println("这是Yun类中的pi:"+y.GetPi());
    }
}

输出结果:
这是我定义的变量pi:3.14
这是Yun类中的pi:1.0

Here we can see that when final modifies a local variable, even if the final modified variable is not initialized at the time of declaration, subsequent initialization is possible, but this is a bad programming habit, and here is just an introduction to you.

When final modifies the properties of a class, if it is not initialized at the time of declaration or in the constructor, the program will definitely report an error. The above program reports an error, but because there is a constructor with parameters, it can still be executed. After initialization, the program can still run and get results, but it is recommended that you develop good programming habits.

import static java.lang.System.out;
import java.util.Random;
class T{
    int i=0;
}
public class Demo {
    static Random rand=new Random();
    final int VALUE_1=9;
    static final int num1=rand.nextInt(10);
    final int num2=rand.nextInt(10);
    final T test=new T();
    final int[]a={1,2,3};
    public static void main(String[] args) {
        Demo demo=new Demo();
        //demo.test=new Test();     //报错,final修饰的对象引用不能重新赋值
        /*for (int i = 0; i < demo.a.length; i++) {
            a[i]=9;                 //报错,final修饰的数组不能重新赋值
        }*/
        System.out.println(demo.VALUE_1);
        System.out.println("num1="+demo.num1);
        System.out.println("num2="+demo.num2);
        Demo newDemo=new Demo();
        System.out.println("newDemo num1="+newDemo.num1);
        System.out.println("newDemo num2="+newDemo.num2);
    }
}

Output result:


9
num1=2
num2=3
newDemo num1=2
newDemo num2=9

In the above code, reassigning the final modified object reference test and the array a will report an error, indicating that the final modification is irreversible.

However, when final modifying the properties of a class, each time an object is defined, as shown in the above code, the num2 of demo and newDemo are different, and it cannot be truly changed. At this time, it can be completely modified by static final. Fix the value. public static final also comes into play to modify global constants.

Another thing to say is that when final modifies a constant, the constant name should be capitalized. When the name is multiple words, it should be separated by an underscore, so that it is easy to distinguish between constants and variables (all capitals are constants, which are clear at a glance and easy for others to read). This is also Java. programming rules.

final method

Feature: final methods cannot be overridden.
Role: When the parent class wants to define a method that cannot be modified by the subclass, it can be modified with fianl. Here is a mention: the private method of the parent class, the subclass is inaccessible, so the private method defaults to the final modification, but the final keyword is omitted.
for example:

import static java.lang.System.out;
import java.util.Random;
class Parents{
    private void doit(){
        System.out.println("父类.doit()");
    }
    public void doit2(){
        System.out.println("父类.doit2()");
    }
    final void doit3(){
        System.out.println("父类.doit3()");
    }
}
class Sub extends Parents{
    private void doit(){
        System.out.println("父类.doit()");
    }
    public void doit2(){
        System.out.println("父类.doit2()");
    }
    /*final void doit3(){
        System.out.println("父类.doit3()");
    }*/
}
public class Demo {
    public static void main(String[] args) {
        Sub s=new Sub();
        s.doit2();
        s.doit3();
        Parents p=s;
        p.doit2();
        //p.doit();     //无法调用
    }
}

The doit3() method in this subclass will report the following error:

    - Cannot override the final method from Parents

That is to say, subclasses cannot override a final modified method.
At the same time, the doit() method of the parent class is rewritten in the subclass. Although no error is reported, an error will be reported when the upward transformation is actually called, so the p.doit() method is not feasible, because the method override must satisfy An object is upcast to its basic type and can call the same method normally, so it cannot be considered as successful coverage here, which also satisfies the statement that the final modified method cannot be overridden.

final class

Features: Classes defined by final cannot be inherited
. Role : used to modify a class that is not allowed to be inherited and modified
. All methods in final classes are implicitly set to final form, but member variables in final classes can be set as non-final Or the final form, or a simple example:

final class Demo {
    int a=3;
    void doit(){

    }
    public static void main(String[] args) {
        Demo demo = new Demo();
        demo.a++;
        System.out.println(demo.a);
    }
}

The output is

4

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325972034&siteId=291194637
Recommended