Java Final keyword

Source: Internet
Author: User

Catalogue

    • Directory
    • Final meaning
    • Final variable
    • Final method
    • Final class
    • Final keyword Benefits

Final meaning

Final is a reserved keyword in Java that can declare member variables, methods, and classes. Once you declare the reference as the final type, you will no longer be able to change the reference. The compiler checks the code, and if you try to initialize the variable again, the compiler will report a compilation error.

Final Variable

It is called a final variable that is declared final for a member variable or a local variable (a variable in a method or in a block of code is called a local variable). The following is an example of a final modified variable:

finalint1;// constValue = 2; The final local variable constValue cannot be assigned.

Additional points:

    1. The final member variable must be initialized at the time of declaration or initialized in the constructor , or the compiler will error.
    2. Cannot assign a value to the final variable again.
    3. All variables in an anonymous class must be final variables.
Final Method

Final can also declare methods. The method name is preceded by the final keyword, which means that the method cannot be overridden by the quilt class. If you think that the functionality of a method is complete enough, and you do not need to change the method in the subclass, you can declare the method as the final type.
The final declaration method is faster than the non-final method because it is statically bound at compile time and does not need to be dynamically bound at run time. Here is an example of the final method:

publicclass Person{    publicfinalvoidprintName() {        System.out.println("wangzhengyi");    }}
Final Class

A class that uses final to decorate is called the final class. The final class is generally functionally complete and cannot be inherited. Many classes in Java are final, such as the String class.

One of the benefits of an immutable class is that it is thread-safe, and you don't need to consider thread-safety issues in multithreaded environments. To create an immutable class, you need to implement the following steps:

    1. Declares a class to be final so that it cannot be inherited.
    2. Declare all members private so that you do not allow direct access to those members.
    3. Do not provide setter methods for variables.
    4. Declare all mutable members as final so that they can be assigned only once.
    5. Initializes all members through the constructor, making deep copy.
    6. In the getter method, do not directly return the object itself, but instead clone the object and return a copy of the object.

Note: The difference between a shallow copy and a deep copy:

  1. Shallow copy (Shallow clone): All variables of the copied object contain the same value as the original object, and all references to other objects still point to the original object. In other words, only the base type of the object is copied, and the object type still belongs to the original reference.
  2. Deep copy (Deep clone): All the variables that are copied contain the same values as the original objects, removing the variables that refer to other objects. Variables that refer to other objects will point to new objects that have been copied, not those that are already referenced. In other words, not only the base type of the object is copied, but the object in the original object is copied as well.

Examples of immutable classes:

ImportJava.util.HashMap;ImportJava.util.Iterator; Public  class finalclassexample {    Private Final intIdPrivate FinalString name;Private FinalHashmap<integer, string> Hmap; Public int getId() {returnId } PublicStringGetName() {returnName }/** * Variable Object access method: Returns the copy of the object * @return */     PublicHashmap<integer, string>Gethmap() {return(Hashmap<integer, string>) Hmap.clone (); }/** * Implement a deep copy of the constructor */     Public Finalclassexample(intID, String name, Hashmap<integer, string> map) { This. id = ID; This. name = name; Hashmap<integer, string> TMap =NewHashmap<integer, string> ();intKey iterator<integer> Iterator = Map.keyset (). Iterator (); while(Iterator.hasnext ())            {key = Iterator.next ();        Tmap.put (Key, Map.get (key)); } This. Hmap = TMap; }/** * Implement a shallow copy constructor */    /* Public finalclassexample (int ID, String name, Hashmap<integer, string> map) {this.id = ID;        THIS.name = name;    This.hmap = map; }    */}
Final keyword Benefits

The following are the advantages of using the final keyword:

    1. The final keyword improves performance. Both the JVM and the Java application cache the final variable.
    2. The final variable can be shared securely in a multithreaded environment without the need for additional synchronization overhead.
    3. With the final keyword, the JVM optimizes methods, variables, and classes.

Java Final keyword

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.