Java Final keyword

Source: Internet
Author: User

Depending on the context, Java's keywordfinal also has subtle differences, but usually refers to "this cannot be changed." "There are two reasons not to change: one is efficiency, and the other is design. Because two reasons are very far apart, the key sub-final may be used by Wu.

Next, let's look at the three scenarios used in FIANL: data, methods, classes.

Final Data

Many programming languages have a way to tell the compiler that a piece of data is constant. Sometimes the constant of data is very practical, such as:

1, a constant at compile time constant

2, one is initialized at execution time, and you don't want it to be changed.

In this case of a compile-time constant, the compiler is able to substitute the constant value into a formula that can be used in whatever it is possible to use, that is, the ability to perform calculations at compile time, which relieves some of the burden of execution. In Java, such constants must be of a basic type and are represented as final. When you define this constant, you must assign a value.

A domain that is static and fianl only occupies a storage space that cannot be changed.

When final is applied to an object reference, rather than the base type, its meaning is somewhat confusing. The use of fianl for a basic type cannot be changed by his value. For object references, the reference cannot be changed, and the object itself can be altered. Once a final reference is initialized to an object, the reference cannot point to another object. Java does not provide constant support for whatever object. This restriction is also common for arrays, which are also objects.

The following examples demonstrate the situation of the FIANL domain. Note that, according to the Convention, a field that is static and fianl (that is, compiler constants) will be capitalized and cut with the following words:

Package reusing;//: reusing/finaldata.java//The effect of final on Fields.import java.util.*;import static Net.mindview. Util. Print.*;class value {int i;//package access public Value (int i) {this.i = i;}} public class FinalData {private static random Rand = new Random (47); Private String ID; Public FinalData (String id) {this.id = ID;} Can be compile-time constants:private final int valueone = 9; private static final int value_two = 99; Typical public constant:public static final int value_three = 39; Cannot be compile-time constants:private final int i4 = Rand.nextint (20); static final int int_5 = Rand.nextint (20); Private Value V1 = new value (11); Private Final Value v2 = new value (22); private static final Value Val_3 = new value (33); Arrays:private Final int[] A = {1, 2, 3, 4, 5, 6}; Public String toString () {return id + ":" + "I4 =" + I4 + ", int_5 =" + int_5; } public static void Main (string[] args) {FinalData fd1 = new FinAldata ("Fd1"); //! fd1.valueone++; Error:can ' t change value fd1.v2.i++; Object isn ' t constant! FD1.V1 = new Value (9); OK--not final for (int i = 0; i < fd1.a.length; i++) fd1.a[i]++; Object isn ' t constant! //! Fd1.v2 = new Value (0); Error:can ' t//! Fd1. Val_3 = new Value (1); Change Reference//! fd1.a = new Int[3]; Print (FD1); Print ("Creating new FinalData"); FinalData fd2 = new FinalData ("Fd2"); Print (FD1); Print (FD2); }}//Output:fd1:i4 = Int_5 = 18Creating new Finaldatafd1:i4 =, Int_5 = 18fd2:i4 = all, Int_5 = 18*/

Because both Valueone and Value_two are fianl basic types with compile-time values, both can be used as compilation-period constants without significant differences. Value_three is a more typical way of defining constants: defined as public, able to be visited by any person, defined as static, emphasizing only one copy, and defined as FIANL, which indicates that it is a constant. Note that the final static base type with a constant initial value (that is, the compile-time constant) is all capitalized and is separated by an underscore between letters and letters.

We can not think that some data is fianl to know its value at compile time. The use of random numbers to initialize the values of I4 and int_5 at execution time is called a description. The case section also shows the difference between defining FIANL data as static and non-static. This difference only appears when the value is initialized within execution, because the compiler treats the compile-time values equally (and they may disappear due to optimizations). This difference is seen when executed. Note that the values I4 in this fd1 and FD2 are unique and are initialized to 15, 13 each time. The value of int_5 is not able to be changed by creating a second FinalData object. This is because he is static and is initialized when the class is loaded (that is, when the class object is first created), not every time it is created.


If it is difficult to see the above examples to understand the parts of my marker color, consider the following examples:

Public class B3 {static random R =new Random (n), final int int1= r.nextint (100),//Generate 0-99 random number static final int int_2= R. Nextint (+);p ublic static void Main (string[] args) {B3 b1=new B3 (); System.out.println ("Int1:" +b1.int1+ "int_2:" +b1.int_2); B3 b2=new B3 ();//b2.int_2=100;//error Assignment System.out.println ("Int1:" +b2.int1+ "int_2:" +b2.int_2);}}

Starting main () first runs the B3 b1=new B3 (), creates the first object of the B3, which initializes the static final int int_2= R.nextint (100), and then initializes the final int int1= R.nextint ( 100), so the result of the first output statement is Int1:12 int_2:66. Next, you create the second object of B3, which also causes the initialization of the members in the B3 class, but the static final int int_2= R.nextint (100), which is not initialized and why it was mentioned earlier. The result of the output is int1:56 int_2:66. The value of the output int_2 two times is the same.

In our first case, V1 to Val_3 to illustrate the meaning of final references. As seen in the main () method, you can change the value of an object array a, but you cannot point a reference to an object. It seems to make the base type fianl more useful than the reference type becomes final.

Java may generate "blank final", the so-called blank final refers to the domain that is declared final but does not give the initial value. The compiler will ensure that the final domain is initialized before use, regardless of the circumstances. But the blank final provides a lot of flexibility in the use of fianl, and for this reason, a fianl domain can be different based on some objects, while maintaining a constant character. The following examples illustrate a point.

class Poppet {private int i; Poppet (int ii) {i = II;}} public class Blankfinal {private final int i = 0;//Initialized Final private final int J;//Blank Final private fin Al Poppet p; Blank final reference//blank finals must is initialized in the Constructor:public blankfinal () {j = 1;//Init Ialize blank Final p = new poppet (1); Initialize Blank Final Reference} public blankfinal (int x) {j = x;//Initialize blank final p = new Poppet (x ); Initialize Blank Final Reference} public static void Main (string[] args) {new blankfinal (); New Blankfinal (47); }} //

Final number of references

in Java, it is possible to specify the number of references in the list of references as final in a declarative manner. This means that you have no change to the object that the parameter points to.

class Gizmo {public void spin () {}}public class Finalarguments {void with (final Gizmo g) {//! g = new Gizmo (); Illegal--G is final} void without (Gizmo g) {g = new Gizmo ();//OK – G not final g.spin (); }//void f (final int i) {i++;}//Can ' t change//You can only read from a final Primitive:int g (final int i) {ret Urn i + 1; } public static void Main (string[] args) {finalarguments bf = new finalarguments (); Bf.without (NULL); Bf.with (NULL); }} //

Method F () G () shows that the base type of the parameter is specified as final is the result of the occurrence: You can read the number of references, but you cannot change the parameters. This feature is used only to pass data to anonymous internal classes.

Final method

There are two reasons for using the final method. The first reason is to lock the method to prevent whatever inherits its meaning from its class. This is a design consideration: you want to ensure that the methods used in inheritance remain intact and are not overwritten.

The second reason for the previous recommendation to use the final method is efficiency. In early implementations of Java, it is assumed that a method is indicated as FIANL, which allows the compiler to turn all calls to the method into inline calls. When the compiler discovers a final method invocation command, it will run the method invocation mechanism (pressing the reference into the stack, jumping to the method code, and then jumping back and cleaning the parameters in the stack, processing the return value), based on its own deliberate inference, skipping the normal invocation of the Insert program code. and replace the method call with a copy of the actual code in the method body. This will eliminate the overhead of the method call. Of course, assuming that a method is very large and your program code expands, you may not see performance improvements in embedding, because the resulting performance will be reduced by the amount of time spent in the method.

I don't know where the color is. I do not know the person who has seen the idea of Java programming and know to explain the explanation.

In the most up-to-date Java version number, virtual machines (especially hotspot technology) can detect these situations and optimize additional inline calls that eliminate these efficiencies, and therefore no longer need to use the final method for optimization. In fact, such a practice is gradually being discouraged. When using Java SE5/6, you should let the compiler and the JVM handle the efficiency problem, and only if you want to understand the forbidden override, set the method to Fianl.

Final and Privatekeyword

All private methods in a class are implicitly formulated as final. Because you can't access the private method, you can't overwrite it. The ability to add final modifiers to private methods, but this is meaningless.

class Withfinals {//identical to "private" alone:private final void F () {print ("withfinals.f ()");} Also automatically "final": private void G () {print ("WITHFINALS.G ()");}} Class Overridingprivate extends Withfinals {private final void F () {print ("overridingprivate.f ()"); } private void G () {print ("overridingprivate.g ()"); }}class OverridingPrivate2 extends Overridingprivate {public final void F () {print ("overridingprivate2.f ()"); } public void G () {print ("overridingprivate2.g ()"); }}

Overwrite only occurs when a method is part of a base class interface. That is, you must transform an object upward into its base class and strip it in the same way. If a method is private, it is not part of the base class interface. It is only some program code that is hidden from the class, assuming that a private method exists in a base class, and a public,protected or packet access permission method is created with the same name in the derived class, the method simply has the same name as the method in the base class. The base class method is not overridden. Because the private method is inaccessible and has very good concealment, it is considered to exist because of the organizational knot of the class he belongs to, regardless of anything else.

Final class

When you define a class as final, it indicates that you are not going to inherit the class, and that it is not possible for others to do so. In other words, for some reason, you never have to make any changes to the design of the class, or for security reasons, you don't want him to have a subclass.

class Smallbrain {}final class Dinosaur {int i = 7; int j = 1; Smallbrain x = new Smallbrain (); void F () {}}//! Class further extends Dinosaur {}//Error:cannot extend final class ' dinosaur ' public class Jurassic {public static void Main (string[] args) {Dinosaur n = new Dinosaur (); N.F (); N.I = 40; n.j++; }}

Note that the final class domain can be selected as or not final based on the wishes of the individual. The same rules apply to a field that is defined as final, regardless of whether the class is defined as final. However, because final is not inheritable, the methods in the final-decorated class are implicitly set to FIANL, because you cannot overwrite them. In the Fianl class, the method can be added to the final, but this does not produce any meaning whatsoever.

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.