On the final of Javase

Source: Internet
Author: User

Let's look at an interview question first:

  What is the meaning of final? Where can I use it? What are the ways to initialize it?

First we answer this question, and then we explore its why. 

1. Final means "final", "immutable", meaning that the value of a property whose cosmetic class cannot be inherited or decorated cannot be changed.
2. Final can either modify the class or modify the properties.
3. The final variable can initialize the value directly, or it can initialize the value in the constructor method, but only one of them is optional.

All right! Now that we know the answer, let's go to one by one to verify it!

1. Direct initialization of attribute values, classes cannot be inherited:

Package Com.smbea.demo;import org.junit.test;/** * Final modifier attribute and initialize directly * This class cannot be inherited * @author Hapday */public final class final DEMO2 {final int num = 9; @Testpublic void Finaltest () {//this.num = 7;//This sentence is commented because it is reported as the final field Finaldemo2.num Canno  T be assigned error SYSTEM.OUT.PRINTLN (this.num); Output result: 9}}

2. Initialize the constructor for final variables:

Package com.smbea.demo;/** * Final modified property and initialized with the constructor * @author Hapday */public class Finaldemo {final int num;p ublic finaldem O (int num) {System.out.println ("parameterless constructor"); this.num = num; System.out.println (this.num);} public static void Main (string[] args) {new Finaldemo (8);}}

  

On the final of Javase

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.