Java Final keyword

Source: Internet
Author: User

Based on the context. The keywordfinal of Java is slightly different. But it is generally referred to as "This cannot be changed." "The reason does not want to change from two: one is efficiency, and there is a design. There are two reasons for the difference, so the key points are final Wu can use.

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

Final Data

Many programming languages have some kind of method. 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 any calculation that might be used in it, that is. The ability to perform calculations at compile time reduces some of the burden of execution. In Java. Such constants must be of a basic type and be represented as final. When defining this constant. Must be assigned.

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.

And for object references. What cannot be changed is his reference, 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 compile-time constants. And there is no significant difference. Value_three is a more typical way of defining constants: defined as public. Be able to be interviewed by anyone, as static. It is emphasized that only one copy is defined as FIANL, which indicates that it is a constant. Note that there is a constant initial value (that is,. Compile-time constants) The final static base type 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. The class was initialized when it was loaded (that is, when the class object was first created). Instead of every creation, it is initialized.


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 depending on some object. While maintaining a constant and unchanging 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 the same. And will not be 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 call command. It can be inferred from its own discretion. Skipping the normal invocation of the Insert program code and running the method invocation mechanism (pushes the number of participants into the stack and jumps to the method code to run.) Then jump back and clean up the number of references in the stack. Handles the return value) and replaces 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. Suppose a method is very large. Your program code expands, so you may not see the performance improvement that comes with embedding. The resulting performance is 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. The compiler and JVM should be allowed to handle efficiency issues. The method is set to FIANL only if you want to understand the forbidden overlay.

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 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. If you create a public,protected or packet access permission method with the same name in a derived class, the method simply has the same name as the method in the base class, and does not overwrite the base class method.

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 it is not possible for others to do so. Other words. Out of some consideration. Your design for the class never needs to be changed, 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++; }}

Please note that the final class field can be based on personal preference or not final. Whether the class is defined as final or not. The same rule applies to the same definition as the final domain. However. Because final it cannot be inherited. They are final modified class methods that are implicitly being developed fianl because you cannot pay them. The FIANL can join the class method final, but no matter what the meaning.

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.