Thinking in Java---final keyword summary + initialization and class loading

Source: Internet
Author: User

The final keyword can be used to modify basic variables, and references can also be used to modify methods and classes. There are different meanings when modifying different objects, so it is easy to confuse them and make a summary here. Understanding the initialization of variables and the loading mechanism of classes can also give us a global grasp of what happens when a program is run.

One. Final keyword
1.1 Final keyword modifier variable
The final keyword is similar to the const keyword in C + + when it modifies the base variable to indicate that the variable can no longer be changed once it is initialized to a value. When final is used to decorate a reference, it is a little different, it can only mean that once the reference is initialized to point to an object, then the point of the reference can no longer be changed, but the value of the object pointed to is still able to change, the following program demonstrates this.

Package LKL; Public classValue { Public intI Value (inti) { This. i=i; }}package Lkl;import Java.util.Random; Public classfinaltest { Public StaticRandom Rand =NewRandom ( $); PublicFinalintValueone=9;//  final modifier common variable     PublicFinalintValuetwo = Rand.nextint ( the);///  Final modified normal variable, not necessarily assigned to a constant value     PublicFinal Value val =NewValue (1);//  Final Modified reference     Public StaticFinalintint_1=Ten; ///final and static are used to represent constants that can be determined at compile time     Public Static void Main(string[] args) {Finaltest ft=NewFinaltest ();//ft.valueone++; Attempting to modify the value of a final basic variable, ErrorSystem. out. println (Ft.valuetwo); ft.val.i++;///   Modify the value of the final reference point to the object is Yes        //ft.val=new Value (2);//Attempt to modify the point of the final decorated reference, Error}}

In the above code there is also a case where static and final work together to modify a variable, and this variable occupies only a certain amount of storage space that cannot be modified, called the compile-time constant.
A variable of the final type in Java can also be initialized at declaration time, and the initialization process can be placed in the constructor (all constructors must have initialized statements). This also guarantees that the variables will definitely be initialized before they are used. The advantage is that you can assign different values to the final variable depending on the situation. This final variable is called "blank final".
The following code demonstrates this scenario:

 PackageLKL;ImportJava.util.Random; Public  class finaltest {     Public Final intI Public Final intJ Public finaltest() {i=0; j=0; } Public finaltest(intIintj) { This. i=i; This. j=j; } Public Static void Main(string[] args) {Finaltest ft=NewFinaltest (); Finaltest FT1 =NewFinaltest (1,2); System.out.println ("Ft:i, J"+ft.i+" "+FT.J); System.out.println ("Ft1:i,j"+ft1.i+" "+FT1.J); }}

Finally there is a final use to modify the parameter variables, which means that you cannot change the object that the argument reference points to in the method. The formal parameter at this time is read-only and not writable, as shown in the following code:

 PackageLKL;ImportJava.util.Random; Public  class finaltest {      PublicValue with(FinalValue val) {val=NewValue (2);/// try to change Val's point, Error         returnVal } PublicValueW(FinalValue val) {returnVal } Public int Go(Final inti) {i++;/// try to change the value of I, Error         returnI } Public int F(Final inti) {returni+1; } Public Static void Main(string[] args) {    }}

1.2 Final modification methods and classes
Final is used to decorate the method, which means that the class cannot be overridden (overwritten). This ensures that the method behaves unchanged in inheritance. All private methods in the parent class are implicitly specified as final. For private methods, if we define a method in the subclass that is exactly the same as the It is also not called rewriting, but rewriting defines a new method. But for the final decorated method, we are not allowed to rewrite in the subclass. So the override is only for the parent class interface that is visible in the subclass.

 PackageLKL; Public  class Base {      Private void F() {System.out.println ("Base.private ()"); } Public Final void g() {System.out.println ("base.final ()"); }} PackageLKL; Public  class OverringBase1 extends Base{    Private void F() {System.out.println ("overringbase1.f ()"); } Public Final void g(){///errorSystem.out.println ("OVERRINGBASE1.G ()"); }}

It is much simpler for the final modifier class, and we just need to know that if a class is final decorated then the class cannot be inherited, and of course all the fields in that class are final by default.

Two. Initialization and loading of classes.
Every class in Java has its own compiled code, and then if we want to use this class, we need to load the compiled code file. When the first object of a class is declared, or when a static variable of a class is called, the class is initialized, and each class is initialized only once.
If a class has a base class, the base class is loaded in the process of loading the class, and if the base class has a parent class, the parent class is loaded first.
In this process, starting with the original base class, the static variables for all classes are initialized.
Initialization of other variables: When an object is created, all the basic types in the object are set to default values, the object's reference is set to NULL, and if there is an initialization block, the initialization block is executed, and the constructor is initialized at the end. Variables are initialized in their order. The following code demonstrates the process of initialization:

Package LKL; Public classBase { Public intI=9;///   Specify a default value first     Public intJ Public intK Public intD Public Base(intx) {j=i;            I=x;    K=i; } {i=Ten;//   initialization blockD=i; } Public Static void Main(string[] args) {Base be =NewBase (2);///   The value of the output indicates that the initialization block is executed first, and then the constructorSystem. out. println (be.j+" "+" "+be.k+" "+BE.D); }}

Thinking in Java---final keyword summary + initialization and class loading

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.