The difference between static final and final 2016.12.07

Source: Internet
Author: User

When you learn Java, you are often confused by modifiers, which summarize the difference between static final and final.

1, static emphasis only one copy, final description is a constant, final definition of the basic type of the value is immutable, but the value of the reference object defined by the fianl can be changed, as an example to illustrate:

 package   difstaticfinalandfinal;  class   Selfcounter { private  static  int   counter;  private  int  Id=counter++;  public   String toString () { return  "Selfcounter:" +ID; }}
 package   difstaticfinalandfinal;  class   Withfinalfields {  static final    selfcounter wffs=new      Selfcounter ();    final    selfcounter wff=new "        Span style= "COLOR: #000000" > Selfcounter ();  public   String toString () { return  "wff=" +wff+ "\ n wffs=" +wffs; }}

Main function:

 Package difstaticfinalandfinal;  Public class staticfinal {    publicstaticvoid  main (string[] args) {        System.out.println ("First Object:");        System.out.println (new  withfinalfields ());        System.out.println ("Second Object:");        System.out.println (new  withfinalfields ());}    }

Operation Result:

First object:wff= selfcounter:1, wffs= selfcounter:0Second object:wff= Selfcounter:2, Wffs= selfcounter:0

Analyze why the WFF two run results are different, and wffs two times the same result?

Because wffs this container is defined with static final, static emphasizes only one copy, so there is only one value,

The final modified reference is changeable, so the value of the WFF is changeable, which is the difference between the final modifier base type and the reference.

The difference between static final and final 2016.12.07

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.