Final usage in Java

Source: Internet
Author: User
Tags arrays definition constant final

Many programming languages have their own way of telling the compiler that a certain data is "constant." The constants are mainly used in the following two areas:
(1) The compile-time constant, which never changes
(2) a value initialized at runtime, and we do not want it to change
for the compile-time constants, the compiler (program) can "encapsulate" the constant value into the desired computation process. That is, the calculation can be performed ahead of time during compilation, saving some overhead at runtime. In Java, these forms of constants must belong to the basic data type (primitives) and are expressed in the final keyword. When you define such a constant, you must give a value.
both static and final fields can store only one data and must not be changed.
If you use final instead of the underlying data type with the object handle, it's a bit confusing. For a basic data type, final will change the value to a constant, but for an object handle, final will turn the handle into a constant. When declaring, the handle must be initialized to a specific object. And you can never turn a handle into another object. However, the object itself can be modified. Java does not provide any means to turn an object directly into a constant (however, we can write a class ourselves so that the objects in it have a "constant" effect). This restriction also applies to arrays, which also belong to objects.
The following is an example of the final field usage:
 

: Finaldata.java//The effect of final on fields class Value {int i = 1;}
  public class FinalData {//Can is Compile-time constants Final int i1 = 9;
  static final int I2 = 99;
  Typical public constant:public static final int I3 = 39;
  cannot be compile-time constants:final int i4 = (int) (Math.random () *20);
  
  static final int i5 = (int) (Math.random () *20);
  Value V1 = new value ();
  Final Value v2 = new value ();
  Static final Value v3 = new value (); //! Final Value v4;

  Pre-java 1.1 Error://No initializer//arrays:final int[] A = {1, 2, 3, 4, 5, 6};
  public void print (String id) {System.out.println (id + ":" + "I4 =" + I4 + ", i5 =" + i5);
    public static void Main (string[] args) {FinalData fd1 = new FinalData (); //! fd1.i1++; Error:can ' t change value fd1.v2.i++;
    Object isn ' t constant! FD1.V1 = new Value (); OK--not final for (int i = 0; i < fd1.a.length i+ +) fd1.a[i]++;
    Object isn ' t constant! //! Fd1.v2 = new Value (); Error:can ' t//! Fd1.v3 = new Value (); Change Handle//!

    fd1.a = new Int[3];
    Fd1.print ("Fd1");
    SYSTEM.OUT.PRINTLN ("Creating new FinalData");
    FinalData fd2 = new FinalData ();
    Fd1.print ("Fd1");
  Fd2.print ("Fd2"); }
} ///:~

Since both I1 and I2 are basic data types with final attributes and have compile-time values, they are not any different in any import mode except that they can be used as a constant at compile time. I3 is a more typical way for us to experience the definition of such constants: public means that they can be used outside the package; Static emphasizes that they have only one; and final shows that it is a constant. Note for fianl static basic data types that contain fixed initialization values (that is, compile-time constants), their names are all capitalized by rule. Also note that i5 is unknown during compilation, so it has no capitalization.
It is not possible to assume that its value can be known at compile time because the attribute of something is final. I4 and i5 prove it to everyone. They use randomly generated numbers during run time. This part of the example also reveals the difference between setting the final value to static and not static. This difference is revealed only if the value is initialized during runtime. Because the value of the compile period is considered by the compiler to be the same. This difference can be seen from the output:

FD1:I4 = i5 = 9
Creating new FinalData Fd1:i4 =
, i5 = 9
Fd2:i4 = ten, i5 = 9

Note for FD1 and FD2, the I4 value is unique, but the i5 value is not changed because another FinalData object was created. That is because its properties are static and initialized at load time, rather than when each object is created. The
variable from v1 to V4 reveals to us the meaning of the final handle. As you can see in main (), you can't think that because V2 belongs to final, you can't change its value any more. However, we really can't bind v2 to a new object because its properties are final. This is the exact meaning of final for a handle. We will find that the same meaning applies to arrays, which are just another type of handle. Turning a handle to final looks less useful than making the base data type final.

2. Blank Final
Java 1.1 allows us to create "blank final", which belong to some special fields. Although declared final, it did not get an initial value. In either case, the blank final must be properly initialized before it is actually used. And the compiler will take the initiative to ensure that this provision is implemented. However, blank final has the greatest flexibility for all applications of the final keyword. For example, a final field located within a class can now be different for each object, while still maintaining its "invariant" nature. An example is listed below:
 

: Blankfinal.java
//"Blank" Final data members

class Poppet {}

class Blankfinal {
  final int i = 0;// Initialized final
  final int J;//Blank final
  final poppet p;//Blank final handle
  //Blank finals must Itialized
  //In the constructor:
  blankfinal () {
    j = 1;//Initialize blank final
    p = new poppet (); 
   
    }
  blankfinal (int x) {
    j = x;//Initialize blank final
    p = new poppet ();
  }
  public static void Main (string[] args) {
    blankfinal bf = new Blankfinal ();
  }
///:~
   

Now force us to assign to final--either an expression in the definition of the field or in each builder. This ensures that the final field gets the correct initialization before it can be used.

3. Final independent variable
Java 1.1 allows us to set our arguments to the final property by making an appropriate declaration of them in the list of arguments. This means that in the interior of a method, we cannot change what the argument of the variable handle points to. As shown below:

: Finalarguments.java
//Using "final" with method arguments

class Gizmo {public
  void Spin () {}
}

public class Finalarguments {
  void with (Final Gizmo g) {
    //! g = new Gizmo ();//illegal--the G is final
    g.spin ( );
  }
  void without (Gizmo g) {
    g = new Gizmo ();//OK--G not final
    g.spin ();
  }
  void f (final int i) {i++}//Can ' t change
  //can only read from a final primitive:
  int g (final int i) {return i + 1;}
  public static void Main (string[] args) {
    finalarguments bf = new Finalarguments ();
    Bf.without (null);
    Bf.with (null);
  }
///:~

Note that the final argument can still be assigned a null (NULL) handle at this time, and the compiler will not capture it. This is the same thing that we do with non-final arguments.
Methods F () and g () show us what happens when the primitive type's arguments are final: we can only read from the variable and not change it.

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.