Deep parsing of the final keyword usage in Java programming _java

Source: Internet
Author: User
Tags garbage collection inheritance int size rand

When declaring properties, methods, and classes in Java, you can decorate them with the final keyword. The final variable is a constant and can only be assigned one time; The final method cannot be overridden by a quilt; the final class cannot be inherited.
1. The final member
declares the final field to help the optimizer make better tuning decisions, because if the compiler knows that the value of the field does not change, it can safely cache the value in the register. The final field also provides an additional level of security by having the compiler force the field to read-only.
&NBSP
1.1 about final member assignment
1) in Java, normal variables can be initialized by default. But final-type variables must be explicitly initialized.
&NBSP
2) The final member can and can only be initialized once.
&NBSP
3) The final member must be declared (directly assigned to the final variable when it is defined) or initialized in the constructor, and cannot be initialized elsewhere.
Example 1 Bat.java

  At> list; Because you want to initialize in the constructor, you cannot assign the
 
  Bat () {
    i =;
    List = new linkedlist<bat> ();
  }
 
  Bat (int II, list<bat> l) {
    i = II;
    list = l;
  }
 
  public static void Main (string[] args) {
    bat b = new Bat ();
    B.list.add (New Bat ());
    b.i=25;
    B.list=new arraylist<bat> ();
    System.out.println ("i=" + b.i + "List Type:" + b.list.getclass ());
    b = New Bat (new arraylist<bat> ());
    B.list.add (New Bat ());
    System.out.println ("i=" + b.i + "List Type:" + b.list.getclass ());
  }


Results:

i=100 list Type:class java.util.LinkedList
i=23 List type:class java.util.ArrayList


In the main method, there are two lines of comment out, if you remove the annotation, the program will not be compiled, which means that, whether it is the value of I or the type of list, once initialized, it can not be changed. However, B can specify the value of I or the type of list by reinitialization.

Invalid initialization for 1.2 final reference field
It is a bit cumbersome to use the final field correctly, especially for object references whose constructors can throw exceptions. Because the final field must be initialized only once in each constructor, if the final object references a constructor that might throw an exception, the compiler may complain that the field is not initialized. Compilers are generally more intelligent enough to discover that initialization occurs only once in each branch of two mutually exclusive branches of code (for example, if...else blocks), but it is generally not so "tolerant" to try...catch blocks.
The following code usually has a problem.

Class Thingie {public
  static thingie Getdefaultthingie () {return
    new thingie ();
  }
}
 
public class Foo {
  private final thingie thingie;
 
  Public Foo () {
    try {
      thingie = new Thingie ();
    } catch (Exception e) {
      thingie = thingie.getdefaultthing IE ();//error:the final field thingie may already have been assigned
    }
  }


You can change that.

public class Foo {
  private final thingie thingie;
 
  Public Foo () {
    thingie tempthingie;
    try {
      Tempthingie = new Thingie ();
    } catch (Exception e) {
      tempthingie = Thingie.getdefaultthingie ();
    }
    thingie = Tempthingie;
  }


1.3 about final member use
when you define a variable in a class, precede it with the final keyword, that is, once the variable is initialized, it cannot be changed, and the immutable meaning here is immutable for the base type, and the reference to the object variable cannot be changed. However, the object itself can be modified, and Java does not provide a way to make any object immutable. This restriction is also appropriate for arrays, and it is also an object.
Example 2

private final int val_one=9;
private static final int val_two=99;
public static final int val_three=999;

Because Val_one and Val_tow are final original types with compile-time values, they can both be used as compile-time constants and have no significant difference. Val_three is a more typical way of defining constants: defined as public, can be used outside of packages, defined as static to emphasize only one copy, and defined as final to show that it is a constant. The
final-marked variable becomes a constant, but this "constant" can only be used within the class and cannot be used directly from outside the class. But when we tag a constant with public static final, this constant becomes a global constant (a field that is both static and final occupies a space that cannot be changed). and the constants defined in this way can only be assigned when defined, not anywhere else.
Example 3

Class Value {
  int i;
 
  Public Value (int i) {
    this.i = i;
  }
}
 
public class FinalData {
  private static Random rand = new Random ();
 
  Private String ID;
 
  Public FinalData (String ID) {
    this.id = ID;
  }
 
  Private final int i4 = Rand.nextint;
 
  static final int i5 = rand.nextint;
 
  Public String toString () {return
    ID + ":" + "I4:" + i4 + ", i5=" + i5;
  }
 
  public static void Main (string[] args) {
    FinalData fd1 = new FinalData ("Fd1");
    System.out.println (FD1);
    SYSTEM.OUT.PRINTLN ("Creating new FinalData");
    FinalData fd2 = new FinalData ("Fd2");
    System.out.println (FD1);
    System.out.println (FD2);
  }


Results

Fd1:i4:6, i5=3
creating new FinalData Fd1:i4:6, i5=3 fd2:i4:17
, i5=3

The Example section shows the difference between defining a final value as static (i5) and non-static (I4). This difference is only apparent if the value is initialized during the runtime, because the compiler treats the compile-time values equally. (And they may disappear because of optimizations.) When you run the program, you'll see the difference. Note that in FD1 and FD2, the value of i5 cannot be changed by creating a second FinalData object. This is because it is static and is initialized at Mount time, not every time a new object is created.
Example 4

Class Value {
  int i;
 
  Public Value (int i) {
    this.i = i;
  }
}
 
public class ... {
  Private value v1=new value (one);
  Private final value V2=new value (a);
  private static final value V3=new value (a);
  ..
}
 
public static void Main (string[] args) {
  ...
  fd1.v2.i++;//ok--object isn ' t constant!
  Fd1.v1=new value (9);//ok--not final
  fd1.v2=new value (0);//error:can ' t change reference
  fd1.v3=new value (1) ;//error:can ' t change reference
  ...
}

The variables from V1 to V3 illustrate the significance of the final reference. As you can see in main (), you can't think that you can't change the value of V2 because it's final. Because it is a reference, final means that you cannot point the V2 again to another new object.
Example 5

public class ... {
  Private final int[] a={1,2,3,4,5,6};
  ..
}
 
public static void Main (string[] args) {
  ...
  for (int i=0;i<fd1.a.length;i++)
 fd1.a[i]++;//ok--object isn ' t constant!
  Fd1.a=new int[3];//error:can ' t change reference ...
}

An array has the same meaning (you can change its value, but not point to a new object), and arrays are another reference.

1.4 Resolving the limitations of the final array
Although an array reference can be declared final, the elements of that array are not. This means that exposing the public final array fields or using their methods to return references to those fields is not immutable.

Not immutable--the states array could is modified by a malicious
//Callerpublic
class Dangerousstates {
   private Final string[] states = new string[] {"Alabama", "Alaska", "ect"};
 
  Public string[] GetStates () {return
    states
  }}


Similarly, although an object reference can be declared as a final field, the object it references may still be mutable. If you want to use the final field to create an immutable object, you must prevent the reference of an array or variable object from "escaping" your class. A simple way to do this without having to clone the array repeatedly is to turn the array into a List.

Immutable--Returns an unmodifiable List insteadpublic
class Safestates {
  Private final string[] states = new String[] {"Alabama", "Alaska", "ect"};
 
  Private final List statesaslist = new Abstractlist () {public
    Object get (int. N) {return
      states[n];
    }
 
    public int size () {return
      states.length;
    }
  };
 
  Public List getstates () {return
    statesaslist
  }}


1.5 about final parameter use
Another use is to define that the parameters in the method are final, for a variable of the base type, this does not make any sense, because a variable of the base type is passed as a value when the method is invoked, which means that you can change the parameter variable in the method without affecting the calling statement, but for the object variable, is useful because the object variable passes its reference when it is passed, so your modification of the object variable in the method also affects the object variable in the calling statement, and when you do not need to change the object variable as a parameter in the method, the explicit use of final declaration will prevent you from inadvertently modifying the calling method.

1.6 About parameter variables in the inner class
In addition, when the internal class in the method uses the parameter variable in the method, the parameter variable must be declared final before it can be used.
Example 6 Inclass.java

 public class Inclass {void Innerclass (final String str) {class IClass {IC
      Lass () {System.out.println (str);
  } IClass IC = new IClass ();
    public static void Main (string[] args) {Inclass inc = new Inclass ();
  Inc.innerclass ("Hello"); }
}

2. Final method
2.1final method Use
1 To ensure that the behavior of a function remains unchanged during inheritance and cannot be overwritten (overridding), the final method can be used.

2 All private and static methods in class are final.

2.2 Final and Private keyword
all private methods in a class are implicitly specified to be final. Because the private method cannot be taken, it cannot be overwritten.
Overwrite appears only if a method is part of the interface of the base class. That is, you must be able to transition an object up to its base type and invoke the same method. If a method is private, it is not part of the interface of the base class. It's just some code hidden in the class, just with the same name. However, if you generate a public, protected, or package access method in the same way as the derived class, the method does not produce a "just the same name" scenario that appears in the base class. At this point, you do not overwrite the method, only to generate a new method. Because private methods cannot be touched and can be effectively hidden, nothing else needs to be considered except to think of it as the cause of the organization of the class to which it belongs.
3. Final class
When you define the whole of a class as final, the class cannot be inherited. And because the final class prohibits inheritance, all methods in the final class are implicitly specified as final because they cannot be overwritten.
Final is used for classes or methods to prevent links between methods from being corrupted. For example, suppose that the implementation of a method of class X assumes that method M will work in some way. Declaring X or M final will prevent the derived class from redefining M in this way, causing X to work abnormally. Although it may be better to implement X without these internal dependencies, this is not always feasible, and using final can prevent such incompatible changes in the future.

The difference between ps:final,finally and finallize

    The final
    1. is used to declare properties, methods, and classes that indicate that the property is not mutable, that the method cannot be overridden, and that the class cannot be inherited.  The
    2. finally is the exception-handling statement structure that represents the part that is always executed. The
    3. finallize representation is a method of the object class that is invoked when it is executed in the garbage collection mechanism.
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.