Java keyword final, static usage summary

Source: Internet
Author: User

First, final
Depending on the context of the program, the Java keyword final has the meaning of "This cannot be changed" or "final state", which can be used to modify non-abstract classes, non-abstract class member methods, and variables. You may need to stop the change in two ways: design or efficiency.
The final class cannot be inherited, there are no subclasses, and the methods in the final class are final by default.
The final method cannot be overridden by a method of a class, but can be inherited.
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.
Final cannot be used to modify a construction method.
Note: The private method of the parent class can also inherit from the child class, except that the subclass does not have direct access to the private method that inherits from the parent class, but can still be called by the public method of the original parent class. The private (final decoration) method of the parent class can be overridden by the quilt class. However, if the parent class is public or final (the default decorated +final) type, the method cannot be overwritten. The method in the class referred to in the book can also be declared final. If you do this, subclasses cannot override this method "refers to public Final and final methods cannot be overwritten.
1. Final class
The final class cannot be inherited, so the member methods of the final class have no chance of being overwritten, and the default is final. In the design class, if the class does not need to have subclasses, the implementation details of the class are not allowed to change, and it is certain that the class will not be extended, then it is designed as the final class.
2. Final method
If a class does not allow its subclasses to overwrite a method, you can declare this method as the final method.
There are two reasons for using the final method:
First, lock the method to prevent any inherited classes from modifying its meaning and implementation.
Second, efficient. The compiler goes into an inline mechanism when it encounters a call to the final method, greatly improving execution efficiency.
For example:

Java Code

1  Public classTest1 { Public Static voidMain (string[] args) {//TODO Auto Generate method stub} public void F1 () {System.out.println ("F1");}//method not covered by quilt class public final void F2 () {System.out.println ("F2"),} public void F3 () {System.out.println ("F3");} private void F4 () {System.out.println ("F4");}} public class Test2 extends Test1 {public void F1 () {System.out.println ("Test1 Parent class method F1 is overwritten!");} public static void Main (Stri Ng[] args) {Test2 t=new Test2 (); T.f1 (); T.f2 ();//call the final method inherited from the parent class t.f3 ();//call a method that inherits from the parent class .//t.f4 ();//The call failed to inherit from the parent class}}
View Code

3. Final variable (constant)
A constant is represented by a final modified member variable, which cannot be changed once the value is given!
There are three final modified variables: Static variables, instance variables, and local variables, representing three types of constants, respectively.
As you can see from the example below, once the initial value is given to the final variable, it cannot be changed.
In addition, when the final variable is defined, it can be declared without giving the initial value, which is also called the final blank, and in any case the compiler ensures that the blank final must be initialized before it is used. However, final whitespace provides greater flexibility in the use of the final keyword final, so that the final data members in a class can be implemented differently depending on the object, but with the same characteristics that remain constant.

Java Code

1  PackageOrg.leizhimin; Public classTEST3 {Private FinalString s= "final instance variable S";Private Final inta=100; Public Final intb=90; Public Static Final intc=80;Private Static Final intd=70; Public Final intE//final blank, the initial object must be initialized with a public Test3 (int x) {e=x;}/** * @param args */public static void main (string[] args) {Test3 T=new Test3 (2); //t.a=101;//error, the value of the final variable cannot be changed once it is given//t.b=91;//error, the value of the final variable cannot be changed once it is given//t.c=81;//error, the value of the final variable cannot be changed once it is given//t.d=71;//error, the value of the final variable cannot be changed System.out.println (T.A) once it is given; System.out.println (T.B); System.out.println (T.C); //accessing static fields System.out.println (T.D) with object mode is not recommended;//accessing static fields System.out.println (TEST3.C) with object mode is not recommended; System.out.println (TEST3.D); //System.out.println (TEST3.E);//error because E is final and differs depending on the value of the object. System.out.println (T.E); Test3 t1=new Test3 (3); System.out.println (t1. E); //the final blank variable e differs from the object by its private void test () {System.out.println (new Test3 (1)). A); System.out.println (TEST3.C); System.out.println (TEST3.D); } public void Test2 () {final int A;//final blank, the final int b=4 is assigned when needed;//the case of local constants--final for local variables final int c;//final blank, has not been assigned. a=3;//a=4, error, has been assigned value.//b=2, error, has been assigned value.} }
View Code


4. Final parameters
When the function parameter is the final type, you can read it using the parameter, but you cannot change the value of the parameter.

Java Code

1  Public class  Public Static void New  Public void F1 (finalint///i is the final type and the value is not allowed to change.) System.out.print (i); } }
View Code

Second, static
static means "global" or "static" meaning, used to decorate member variables and member methods, but also to form static blocks of static code, but there is no concept of global variables in the Java language. The
member variables and member methods that are modified by static are independent of any object of the class. That is, it does not depend on class-specific instances and is shared by all instances of the class. As long as this class is loaded, the Java virtual machine can find them based on the class name in the method area of the run-time data area. Therefore, a static object can be accessed before any of its objects are created, without referencing any objects. The
static member variables and member methods that are decorated with public are essentially global variables and global methods, and when you declare an object of its class, you do not generate a copy of the static variable, but all instances of the class share the same static variable. The
static variable can have a private adornment before it, which means that the variable can be used in a static block of code in a class, or in other static member methods of a class (which can also be used in non-static member methods – nonsense), but it is important that it cannot be directly referenced in other classes through the class name. In fact, you need to understand that private is the access permission limit, static means do not instantiate can be used, so it is easier to understand more. Static plus other access keyword effects and so on. The
Static-decorated member variables and member methods are customarily referred to as static variables and static methods, which can be accessed directly through the class name, with access to the syntax:
class name. static method Name (parameter list ...) The
class name. Static variable name
represents a static block of code with a static decorated code block that executes when the Java Virtual Machine (JVM) loads the class (very useful, hehe).
1, static variable
According to whether the static class member variable classification can be divided into two: one is the static modified variable, called a statically variable or a class variable, and the other is not a static modified variable, called the instance variable. The difference is that the
has only one copy of the static variable in memory (saving memory), the JVM allocates only one memory at a time, the memory allocation of the static variable is completed during the loading of the class, can be accessed directly (conveniently) by the class name, and, of course, is accessible through the object (but this is not recommended).
For instance variables, when an instance is not created, the instance variable is allocated once, and the instance variable can have multiple copies in memory without compromising (flexibility).

2. Static method
Static methods can be called directly from the class name, and any instance can also be called, so a static method cannot use the This and Super keywords, and cannot directly access the instance variables and instance methods of the owning class (that is, member variables and member methods without static). Only static member variables and member methods of the owning class can be accessed. Because instance members are associated with specific objects! This need to understand, want to understand the truth, not the memory!!!
Because the static method is independent of any instance, the static method must be implemented, not abstract.

3. Static code block
A static block of code is also called a code block, which is an independent block of static blocks in a class that is separate from a class member, can have more than one position, it is not in any method body, and the JVM executes these static blocks of code when the class is loaded, and if there are multiple static blocks of code, The JVM executes them sequentially in the order in which they appear in the class, and each code block is executed only once. For example:

Java Code

 1  public  class  TEST5 {private  int  A; private  int  B; static  {test5.a=3; System.out.println (a); TEST5 t=new  Test5 (); T.F (); t.b=1000; System.out.println (T.B); } static  {test5.a=4; System.out.println (a); } public  static  void  main (string[] args) {//  TODO automatically generate method stub} static{test5.a=5; System.out.println (a); } public void F () {System.out.println ("Hhahhahah");}}  
View Code

Operation Result:
3
Hhahhahah
1000
4
5
Static code blocks allow you to assign values to some static variables, and finally take a look at these examples, all in a static Main method, so that the JVM can be called directly without creating an instance when it runs the main method.
4. What does static and final piece mean?
Static final is used to modify member variables and member methods, which can be simply understood as "global constants"!
For variables, this means that once a value is given it cannot be modified and is accessible through the class name.
For methods, the representation is not overwritten and can be accessed directly through the class name.

Java keyword final, static usage summary

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.