12.1 The final keyword

The concept of final:

After some classes are described, they do not want to be inherited, or some methods in some classes are fixed and do not want to be rewritten by subclasses. Can be modified with final

The keyword final, final means final, immutable. final is a modifier that can be used to modify classes, members of classes, and local variables.


final features:

Final modified classes cannot be inherited, but they can inherit from other classes.

class Yy {}

final class Fu extends Yy{} // Can inherit the Yy class

class Zi extends Fu {} // Cannot inherit Fu class

 

The final modified method cannot be overridden, but the parent class has no final modified method, and the subclass can add final after overriding.

class Fu {

    // Final modified methods cannot be overridden, but can be inherited and used

    publicfinalvoid method1(){}

    publicvoidmethod2(){}

}

class Zi extends Fu {

    //Override method2 method

    publicfinalvoid method2(){}

}

 

Final-modified variables are called constants, and these variables can only be assigned a value once.

final int i = 20;

i = 30; // Assignment error, final -modified variables can only be assigned once

 

The variable value of the reference type is the object address value. The address value cannot be changed, but the object attribute value in the address can be modified.

final Person p = new Person();

Person p2 = newPerson();

p = p2 ; // The final modified variable p , the recorded address value cannot be changed

p . name = " Xiao Ming " ; // You can change the value of the name attribute in the p object

p cannot be another object, and the value of the name or age attribute in the p object can be changed.

 

To modify member variables, you need to assign values ​​before creating the object, otherwise an error will be reported. (When there is no explicit assignment, multiple constructors need to assign values ​​to them.)

class Demo {

    // direct assignment

    end int m = 100;

   

    //The final modified member variable needs to be assigned before the object is created, otherwise an error will be reported.

    end int n ;

    publicDemo (){

        // You can assign a value to the variable n in the constructor called when the object is created

        n = 2016;

    }

}


Guess you like

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