Getting started with JavaSE 22: Java object-oriented final keywords

Source: Internet
Author: User

Getting started with JavaSE 22: Java object-oriented final keywords

In Java programming, we sometimes hope that some data cannot be changed, and final will be useful at this time. Final is java

Keyword, which indicates that this part cannot be modified. There are two reasons for not wanting to be changed: efficiency and design. There are three cases of using final: Change

Amount (final variable is a constant), method, class.

One final keyword

Final is a reserved keyword in Java. It can declare member variables, methods, classes, and local variables. Once you make the reference declaration final, you

The reference cannot be changed. The Compiler checks the Code. If you attempt to initialize the variable again, the compiler reports a compilation error.

2. final variable

Any declared final variable for member variables or local variables (variables in the method or code block are called local variables) is called final variables. Final

Variables are often used together with static keywords as constants. Declaring final variables helps the optimizer make better optimization decisions, because if the compiler knows

The field value is not changed, so it can safely cache the value in the register. Final variables also provide the amount by letting the compiler force this field to be read-only

Security level. Final is often used together with static to declare constants. You will also see how final improves application performance.

Note the following when modifying variables using the final Keyword:

1) in java, common variables can be initialized by default, but final variables must be explicitly initialized.

2) final member variables can and can only be initialized once.

3) final member variables must be declared (assigned a value directly when final variable is defined) or initialized in the constructor, but not elsewhere.

Initialized.

The following is an example of the final variable. The Code is as follows:

 

Public class Test {final int b1 = 1; // defined String constant final int b2; // final member variable b2 we use the constructor to initialize // constructor Test (int B) {this. b2 = B;} public static void main (String [] args) {Test test = new Test (2); test. b1 = 5; // the final member variable can only be initialized once. out. println (test. b1); System. out. println (test. b2 );}}

Compilation error:

The final variable is read-only. 3. final Method

Final can also declare methods. The final keyword is added before the method, indicating that this method cannot be overwritten by the quilt class method. If you think of a Method

The function is complete enough. If you do not need to change the function in the subclass, you can declare this method as final. The final method is faster than the non-final method because

It has been statically bound during translation, and does not need to be dynamically bound during runtime.

The final method of the parent class cannot be covered by the quilt class. That is to say, the subclass cannot have the same method as the parent class.

The following is an example of the final method. The Code is as follows:

 

Public class Test {public static void main (String [] args) {Student s1 = new Student (); System. out. println (s1.getName () ;}} class Person {// final method public final String getName () {return "person ";}} class Student extends Person {// override the getName method public final String getName () {return "student" ;}} in the parent class Person ";}}

 

Compilation error message:

Four final classes

The class modified using the final keyword is called the final class. Final classes generally have complete functions and cannot be inherited. Many classes in Java are final,

For example, String, Interger, and other packaging classes.

If a class is modified with final, it indicates that the class is the final class, and it does not want or allow others to inherit it. Be secure or otherwise in programming

The reason is that we do not allow any changes to the class, nor want it to have a subclass. In this case, we can use final to modify the class.

For final-modified classes, its member variables can be final or non-final. If it is defined as final, the final data rules are the same.

Suitable for it. Its method will automatically add final, because the final class cannot be inherited, so this is the default.

The following is an example of the final class. The Code is as follows:

 

Class Person {// final method public final String getName () {return "person" ;}} final class Student extends Person {int id = 123; public int getId () {return id ;}} class S extends Student {}

 

Compilation error:

Benefits of five final keywords

The following summarizes some advantages of using the final keyword.
1) The final keyword improves performance. Both JVM and Java applications cache final variables.

2) final variables can be securely shared in a multi-threaded environment without additional synchronization overhead.

3) using the final keyword, JVM will optimize methods, variables, and classes.

4) use the final keyword to create an immutable class. An unchangeable class means that its objects cannot be changed once they are created. String is an unchangeable class

. Immutable classes have many advantages. For example, their objects are read-only and can be securely shared in a multi-threaded environment without additional synchronization overhead.

And other benefits.

Summary of important final knowledge points

1) The final keyword can be used for member variables, local variables, methods, and classes.

2) final member variables must be initialized during Declaration or in the constructor; otherwise, a compilation error will be reported.

3) The final variable cannot be assigned another value.

4) The local variable must be assigned a value during declaration.

5) all variables in the anonymous class must be final variables.

6) The final method cannot be rewritten.

7) The final class cannot be inherited.

8) the final keyword is different from the finally keyword, which is used for exception handling.

9) The final keyword is easy to mix with the finalize () method, which is defined in the Object class and called by JVM before garbage collection.

10) All variables declared in the interface are final.

11) the final and abstract keywords are irrelevant, and the final classes cannot be abstract.

12) the final method is bound at the compilation stage, which is called static binding ).

13) the final variables that are not initialized at Declaration are called blank final variables (blank final variable) and must be initialized in the constructor or called

Use this () for initialization. Otherwise, the compiler reports the "final variable (variable name) needs to be initialized ".

14) declaring classes, methods, and variables as final can improve performance, so that JVM has the opportunity to estimate and then optimize

15) According to Java code conventions, the final variable is a constant, and usually the constant name should be capitalized: private final int COUNT = 10

16) when the set object is declared as final, the reference cannot be changed, but you can add, delete, or change content to it. For example:

 

private final List Loans = new ArrayList();list.add(“home loan”); //validlist.add( "personal loan" ); //validloans = new Vector(); //not valid
The above code is not very understandable?

 

We already know what the final variable, final method, and final class are. Use final when necessary to write faster and better code.

 

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.