The final keyword in Java

Source: Internet
Author: User

Use the final keyword to do the following:

. declaring a class

When you use final to decorate a class, the class cannot be inherited

Final class Example{int Value;public int getValue () {return value;}} The test here wants to inherit example, but example is final, so the compiler will error class test extends example{}

  

. Declaring a method

When you use final to modify a method of a class, the method cannot be overridden by a quilt class

Class example{int value;final public int getValue () {return value;}} Class Test extends Example{public int getValue () {}}//The test class here attempts to override the method Example () of the parent class GetValue, but in the parent class GetValue () uses the final decoration, An error is reported that cannot overwrite the parent class method

  

. Declaring a constant

Class Example{final int value = 100; final int value1;public int setValue () {value = 200;return value;}} The value in the class uses the final decoration, stating that value is a constant, and the method SetValue () attempts to modify the value of values by reporting an error that cannot specify a value for the final variable value during compilation.//  In addition, the final modified value1 initialization is not assigned, also error, because it is a constant, cannot have no value, this situation can be assigned in the construction method, the following class example{final int value;  Example (int value) {this.value = value; }}//Note that only a construction method can assign a value to an uninitialized final variable

  

  

The final keyword in 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.