The final parsing of Java

Source: Internet
Author: User

In Java, the final keyword can be used to decorate classes, methods, and variables (including member variables and local variables).

    1. When a class is decorated with final, it indicates that the class cannot be inherited.
    2. 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.
    3. The final decorated member variable must be initialized at the time of definition or in the constructor, and once the assignment is not changed.
    4. When a variable is defined as a final type, it is used as a constant when it knows its exact value at compile time.

  

Final String a = "Hello"= "Hello"= "HelloWorld"= A + "world"= B + "World"= === e);

Output Result:

True

False

5. The final modified object content is variable, but the object is immutable. Such as:

Final MyClass MyClass = new MyClass ();

MYCLASS.I = myclass.i + 3;

System.out.println (++MYCLASS.I);

Output Result:

4

However, if you re-assign a value to MyClass, the compilation error will occur.

MyClass = new MyClass ();

6. For the method parameter is the final type

  Public void teststring (final  String str) {      + = "333";   } // compilation produces an error and cannot be re-assigned    Public void Teststringbuilder (final  StringBuilder str) {      str.append ("333");} // can be successfully compiled and executed, and output 333

Sum up. I don't think final can change anything but references, not references. When the reference address of the final modified variable is not changed, it is only possible to change the value.

The final parsing of Java

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.