Final modifier, final Modifier

Source: Internet
Author: User

Final modifier, final Modifier

When final modifies a variable, it indicates that the variable cannot be changed once the initial value is obtained,
The final variable cannot be assigned a new value after obtaining the initial value. Therefore, the final modification of the member variable and the modification of the local variable are somewhat different.

5.4.1final member variable

Member variables are initialized with class initialization or object initialization,
WhenClass initializationThe system willTheClass variables are allocated with memory and default values are allocated;
WhenCreate objectThe system willTheAllocate memory for instance variables and assign default values.
Java Syntax:The final modified member variables must be explicitly specified by the programmer.
Summary:
Final-modified class variables. The instance variables can specify the initial values:
Class variables:
-Specify the initial value in the static initialization Block

     final static int;              static{              i = 10;              }
  • Specify the initial value when declaring this type of Variable
final static int i = 10;

Instance variables:
-Non-static initialization Block

 final int i; {      i = 10;}
  • Declare the instance variable
final int i = 10;
  • Specify the initial value in the constructor
Public class FinalVariableTest {final int I; public FinalVariableTest () {I = 10; // If the initialization block has been assigned a value, it cannot be assigned a value in the constructor }}

The instance variable cannot specify the initial value in the static initialization block becauseStatic initialization blocks are static members and cannot access instance variables-non-static members;Class variables cannot specify the initial value in a common initialization block.BecauseThe class variable has been initialized in the class initialization stage. Normal initialization blocks cannot be assigned a value again.

If you plan to initialize final member variables in constructors and initialization blocks, do not access the value of member variables before initialization.

package code;public class FinalErrorTest{    final int age;    {        //System.out.println(age);        age = 6;        System.out.println(age);    }    public static void main(String [] args){        new FinalErrorTest();    }}

I:> javac-d. FinalErrorTest. java
FinalErrorTest. java: 5: error: the variable age may not be initialized.
System. out. println (age );
^
1 error

5.4.2 final local variables
Package code; public class FinalLocalVariable {public void test (final int a) {// The final modified parameters cannot be assigned. The following statement is invalid // a = 5 ;} public static void main (String [] args) {// if the default value is specified when the final local variable is defined, the str variable cannot be assigned the final String str = "hello "; // str = "java"; final double d; d = 44.5; // d = 443.3 ;}}

I:> javac-d. FinalLocalVariable. java
FinalLocalVariable. java: 10: Error: cannot assign value to the final variable str
Str = "java ";
^
1 error
I:> javac-d. FinalLocalVariable. java
FinalLocalVariable. java: 5: error: the final parameter a cannot be assigned.
A = 5;
^
FinalLocalVariable. java: 13: Error: Variable d may have been assigned
D = 443.3;
^
2 errors

Because the parameter is calling this methodThe system completes initialization based on input parameters.Therefore, the form parameter modified with final cannot be assigned a value.

5.4.3 differences between final modification of basic type variables and reference type variables
package code;import java.util.Arrays;class Person{    private int age;    public Person(){}    public Person(int age){        this.age = age;    }    public void setAge(int age){        this.age = age;    }    public int getAge(){        return age;    }}public class FinalReferenceTest{    public static void main(String[]args){        final int[] iArr = {5,6,12,8};        System.out.println(Arrays.toString(iArr));        Arrays.sort(iArr);        System.out.println(Arrays.toString(iArr));        iArr[2] = -8;        System.out.println(Arrays.toString(iArr));        //iArr = null;        final Person p = new Person(45);        p.setAge(21);        System.out.println(p.getAge());        //p = null;    }}

[5, 6, 12, 8]
[5, 6, 8, 12]
[5, 6,-8, 12]
21

The referenced type variables modified by final cannot be assigned a value again, but the content of the object referenced by the referenced type variables can be changed.

5.4.4 execute the final variable of "macro replacement"

For a final variable, whether it is a class variable, instance variable, or a local variable, as long as the variable meets three conditions, the final variable is no longer a variable, it is equivalent to a direct volume.

  • Use final Modifier
  • The initial value is specified when the final variable is defined.
  • The initial value can be determined during compilation.
Package code; public class FinalReplaceTest {public static void main (String [] args) {final int a = 5 + 3; final double B = 1.2/3; final String str = "crazy" + "Java"; final String book = "Crazy Java handout:" + 99.0; final String book2 = "Crazy Java handout" + String. valueOf (99.0); System. out. println (book = "Crazy Java handout: 99.0"); System. out. println (book2 = "Crazy Java handout: 99.0 ");}}

True
False

Since the value 99.0 is explicitly converted to a String when defining the book2 variable, the compiler cannot determine the value of book2 during compilation because the value of this variable needs to call the method of the String class, book2 is not treated as a "macro variable.

Package code; public class StringJoinTest {public static void main (String [] args) {String str1 = "Crazy Java"; String str2 = "crazy" + "Java "; string str3 = str1 + str2; System. out. println (str1 = str2); System. out. println (str1 = str3 );}}

True
False

Since the compiler can determine the str2 value as "Crazy Java" at the compilation stage, the system will let s2 direct to the "crazy Java" string cached in the constant pool, so str1 = str2.
For final instance variables, the effect of "macro variables" is only available if the initial value is specified when the variable is defined.

5.4.5 final Method

The final modifier method cannot be overwritten.If you do not want the subclass to override a method of the parent class for some reason, you can use the final method.
For a private method, because it is only visible in the current class, its subclass cannot access this method, therefore, the subclass cannot override this method. If a subclass defines a method with the same name, same parameter list, and same return value type, it is not a method rewrite, only a new method is redefined.

Package code; public class PrivateFinalMethodTest {private final void test () {}} class Sub extends PrivateFinalMethodTest {public void test () {}} class FinalOverload {// The final modification method cannot be overwritten. It can be overloaded with public final void test () {} public final void test (String agr ){}}
5.4.6 final class

The final-modified class cannot have child classes.For example, the java. lang. Math class is a final class, and it cannot have subclasses.

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.