A detailed explanation of the final keyword usage in Java object-oriented programming _java

Source: Internet
Author: User

In Java, the final keyword is used to declare an object to have invariance (immutable), where objects include variables, methods, and classes, similar to the const keyword effect in C + +.
Immutable means that the state cannot be changed after the object is created
You can consider using the final keyword from three perspectives:

    • The code itself: does not want the final description of the object to show the meaning has been changed
    • Security: Final object has read-only property and is thread-safe
    • Efficiency: The final object itself cannot be modified, and its referenced operations are more efficient

Final variable
When you define final object A, a can only be initialized once, and once initialized, data for a cannot be modified, and if A is a reference type, you cannot rebind other objects.
Final variables that are not initialized are called blank final and, if they are member variables, must be initialized or assigned in the constructor.
Example:

Class Circle {
 static final double PI = 3.1415926;
 Final int radius = 5;
 final int xpos;
 final int yPos;
 public Circle (int x, int y) {
 xpos = x; 
 YPos = y;
 }
}

Final method
When final method is defined, it cannot be overloaded, and the method designer does not want to cause an exception to other related features due to overloading the method.
Example:

Class BaseClass {public
 final void method () {}
}

class DerivedClass extends BaseClass {public
 final void method () {}//Compile error
}

It is important to note that the final method definition does not necessarily produce a inline effect, because whether the method inline depends on the JVM's strategy, rather than the final keyword, it is inaccurate to improve the method efficiency through final design.

Final class
the class X defined by final class X cannot be inherited.
In Java, the string class is designed to final, which is defined as

Copy Code code as follows:

Public class final String extends Object implements Serializable, Comparable<string>, charsequence

Why was string designed to final?
    • Once an instance of a string class is initialized, its contents on the heap cannot be changed, and any method of modifying a String object provided by the string class can only produce a new string object, greatly simplifying the operation of string, and the code is easier to read and understand;
    • String final is necessary to implement string interning (there is only one copy of string values in memory) because there is usually a large number of string objects in the code, and different references point to the same string space, if the string is not final, When the content of a string space changes, all references need to know this situation, the implementation of this mechanism is very complex, will undoubtedly affect the efficiency. String interning can save memory space while also saving time and expense;
    • String is read-only, you do not have to worry about very important content being tampered with.

Inner class and final
when an anonymous inner class is defined within a method, the inner class can only access the final type variable within the method, allowing the Java compiler to capture the value of the variable in advance and save a copy in the inner class, and the internal class's memory space remains intact when the method is destroyed.
Example:

public class Wrapper {public

  static void Main (string[] args) {
   
    //Object obj = null;//Compilation error
    final Object obj = null;
    New Thread (New Runnable () {public
     void run () {
     obj = "Hello";
     }
    }). Start ();
  }


PS: Internal Anonymous class cannot access non final variables outside the problem
This sounds a bit clumsy, in fact, I would like to say some of the Java internal class features.

The reason to think of this topic as long as it is recently reading the JDK source code in the HTTP keepalive, one of the source files Sun.net.www.protocol.http.HttpURLConnection.java inadvertently see the following code.

Final Boolean result[] = {false};
Java.security.AccessController.doPrivileged (New Java.security.PrivilegedAction () {public
  Object run () {
    try {
      InetAddress a1 = Inetaddress.getbyname (H1);
      inetaddress A2 = inetaddress.getbyname (H2);
      Result[0] = a1.equals (A2);
    } catch (Unknownhostexception e) {
    } catch (SecurityException e) {
    } return
    null;
  }
});

return result[0];

The anonymous inner class of Java cannot access the non final variable of the corresponding function. To access external local variable, this variable must first be defined as FIANL, but a definition of final cannot modify the value of the variable in the anonymous inner class, so it is not easy to return some useful values to the anonymous inner class. This code uses a very ingenious approach, which uses arrays to circumvent this restriction, although we cannot modify the reference to the variable of result, but we can modify the contents of the array that the result points to.

Just want to record a little trick of the internal anonymous class to modify external variables. But now that you're here, you might as well go ahead and see what features or limitations the inner classes have.

Before continuing this article, I find it very necessary to clarify some of the Java terms covered in this article, these terms are not very good translated into Chinese, so we still use English to describe.

This is class public
class Javaterm {

  //field or member variable
  private int field;

  Constructor public
  Javaterm () {
  }

  //method public
  void Method () {

    //local variable
    int localvariable = 0;

    Local class
    class Localclass {public
      localclass () {
      }
    }
    //anonymous class
    new Runnable () {public
      void run () {
      }
    }
  }


We're going to focus more on the local class and anonymous class today, and they all belong to inner class.

Java allows us to define a class within a class, known as nested classes (nested Class), nested class can be divided into two categories, one is the static nested class, the other is non-static nest Ed class, also known as inner class. Inner class can also be divided into local class and anonymous class.

Some limitations of the anonymous class

    • A class variable (field/member variable) of a class that contains it can be accessed by a anonymous class
    • a anonymous class cannot access the function that contains it not the final local Variable (local variable)
    • and nested class, the variable defined in anonymous class overrides the variable of the same name in the scope that contains this inner class
    • you can't set it. A semantic static initialization method
    • a anonymous class can have static member variables. This member variable must be a constant (with final modification).
    • a anonymous class can not have constructors
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.