Java Basics-Keyword-final

Source: Internet
Author: User

In Java, the final keyword can be used to decorate classes, methods, and variables (including member variables and local variables). Here's a look at the basic usage of the final keyword in three ways.

1. Modifier class

When a class is decorated with final, it indicates that the class cannot be inherited. In other words, if a class you never let him inherit, you can use final to decorate. Member variables in the final class can be set to final as needed, but note that all member methods in the final class are implicitly specified as the final method.

When using the final modifier class, be careful to choose, unless the class is not intended to be inherited later or for security reasons, try not to design the class as the final class.

2. Modification methods

There are two reasons to use the final method. The first reason is to lock the method in case any inherited class modifies its meaning, and the second reason is efficiency. In earlier versions of Java implementations, the final method was converted to inline invocation. However, if the method is too large, you may not see any performance gains from inline calls. In the recent Java release, these optimizations do not need to be made using the final method.

  The method is set to final only if you want to explicitly prohibit the method from being overwritten in subclasses.

Note: The private method of the class is implicitly specified as the final method.

3. Modifier variables

The modified variable is the place where final is most used. First look at the basic syntax of the final variable:

For a final variable, if it is a variable of the base data type, its value cannot be changed once initialized, and if it is a variable of a reference type, it cannot be pointed to another object after it has been initialized.

In the above section of the code, the re-assignment of the variables I and obj is an error.

final is used to declare properties (constants), methods, and classes, respectively, to indicate that a property must be initialized once it is allocated memory space.

The meaning of the final keyword is "This is immutable" or "final state";

So why stop the change?

The inventor of the Java language may prevent changes for two purposes:

1). Efficiency issues:
Some of the methods of some classes in the JDK are not allowed to be overwritten by the user, the designer may think that the method used is the best method, the user privately covered, or inadvertently covered, will affect the JVM or the system's ability;
2). Design Required:
It is well known that some cases must use the final keyword, such as the parameter passing of an anonymous inner class in a method

"Modifier variable":
The final member variable represents a constant, which can only be assigned once, and the value will no longer change after the value is assigned.
"Modification Method":
The final method cannot be overridden by a class method, but can be inherited.
"Modifier class":
The final class cannot be inherited, there are no subclasses, and all methods in the final class are final. (such as the String Class)

1. Property variables of a class that are final modified without static modification can only be initialized in two cases: (must be initialized)
A. Assigning values at the time it is declared
B. Initialize in constructor

Explain:

When this property is modified to final, not static, it belongs to the resource of the instance object of the class (instance constant), when the class is loaded into memory, this property does not allocate memory space, but only defines a variable a, only when the class is instantiated, this property is allocated memory space, When instantiated, the constructor is executed at the same time, so the property is initialized, and it conforms to the condition that it needs to be initialized when it is allocated memory space and will not change later.

2. Property variables of a class that are static modified and not final modified can only be initialized in two cases: (Can not be initialized)
A. Assigning values at the time it is declared
B. Initializing in static or non-static fast

Explain:
When the property of a class is modified to be static at the same time, he belongs to the resource of the class (class variable), after the class is loaded, the connection is divided into three steps: first verify; then prepare, allocate memory first, then initialize by default, and parse. Finally, class initialization, before class initialization, must ensure that its parent class has been initialized, so the first to initialize the superclass, for the interface, do not have to initialize its parent interface. Class initialization, it puts the class variable initialization statements and static initialization statements into the class initialization method, so if there is no such statement, there is no <clinit> class initialization method, and the constructor is executed when the class is instantiated, so with the constructor, This property is not initialized at this time. The program will error. The static block is executed when the class is loaded and is executed only once, so it can be initialized in the static block.

3. Property variables for classes that are both final and static modified can be initialized in only two cases: (must be initialized)

A. At the time it is defined
B. Initialize in static block of class
C. In particular, when initializing a constructor that throws an exception, it is initially noted, especially when implementing a singleton pattern (which can only be initialized)

 class   a{ private  final  static   a A;  static  { {a  =new   A ();}  catch   (Exception e) { new  runtimeexception (e); //  must have, otherwise the correct initialization of the constant cannot be done   private  A () throws   exception{}}  

Explain:
When the property of a class is modified to both static and final, he belongs to the resource of the class (class constant), then the class is loaded into memory (that is, when the application starts) it is already allocated memory for this property, so the property already exists, and it is final decorated, Therefore, the value must be initialized after the property has been defined. The constructor is executed when the class is instantiated, so this property is not initialized when the constructor is used. The static block is an error when the class is loaded and executes only this time, so the The static block can be initialized.

Final variable = = constant in Java

"Final variable is invariant": final indicates that the value or reference of the variable is unchanged
Some say that the final variable is immutable after the assignment, which can be a basic data type +string or an object
So what does this constant mean?
This invariant refers to the reference, which is the address, and the contents of the referenced object are still mutable. Note: If you are an object, be aware of the class initialization condition at this time
That is, the final variable always points to an object, which is a constant pointer, not a pointer to a constant.

"Final keyword specific application":
"Final+ variable":
In practical applications, this form is very rare.
For example, logger is possible, but seemingly not very practical, perhaps the user still wants to change the logger variable by setter.
"Static+final+ variable":
Constant. Often used.
"Final+ Method":
JDK is commonly used, but it is not used by itself.
"Final+ class":
Helper classes are often used.
"Final parameter passing for anonymous internal classes":
Often used in multithreaded testing.
"Final parameter for method":
Not used.

Extended:

The variables inside the interface are public static final. So you can write this:
public static final int i=10;
Dolly Mix
int i=10; (Can omit part)
Notice that the variable is given an initial value at the time of declaration.

Explain:

First you need to understand what the interface means. An interface is a uniform ' protocol ', and the attributes in the interface are members of the ' protocol '. They are public, static, and final constants. Equivalent to a global constant.
An abstract class is a class that is not ' complete ', equivalent to an interface and a middle layer of a concrete class. That is, to satisfy the abstraction of the interface and to satisfy the concrete implementation.
If an interface can define a variable, but the method in the interface is abstract, the property cannot be modified by behavior in the interface. Some people will say, no relationship, you can modify the properties of an interface by implementing the behavior of the interface's objects. This is of course not a problem, but consider such a situation. If interface A has a static variable A that has public access permissions. According to Java semantics, we can change the value of variable A in the interface without accessing the variable A through the object that implements the interface, through a.a = xxx; As can be done in an abstract class, all objects that implement interface A will automatically have the value of the changed a, which means that a place has changed a, and the value of a in all these objects has changed. If you can modify the value: What is the difference between this and the abstract class, how to embody the higher level of abstraction of the interface, how to embody the unified protocol provided by the interface, then what is the interface of this abstraction to do? Therefore, the interface can not appear in the variable, if there are variables, and the interface provided by the unified abstraction of the idea is inconsistent. Therefore, the attribute in the interface must be constant, can only be read and cannot be changed, so as to provide a uniform property for the object that implements the interface.
In layman's words, what you think is to change is put in your own implementation, not in the interface, interface is just a kind of things of the properties and behavior of a higher level of abstraction. For the modification to close, the extension (different implementation implements) Open, interface is a manifestation of the principle of closure.

Java Basics-Keyword-final

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.