简体   繁体   中英

Final and Static Final usage in Java

This is from the Ex18 of Chapter "Resuing Classes" in "Thinking in Java". The code is as below:

 public class E18 {
  public static void main(String[]args)
   {
    System.out.println("First object:");
    System.out.println(new WithFinalFields());
    System.out.println("First object:");
    System.out.println(new WithFinalFields());
   }

  }

class SelfCounter{
 private static int count;
 private int id=count++;
 public String toString()
 {
    return "self counter"+id;
 }

 }

class WithFinalFields
{
  final SelfCounter selfCounter=new SelfCounter();
  static final SelfCounter scsf=new SelfCounter();

      public String toString()
      {
           return "selfCounter="+selfCounter+"\nscsf="+scsf;
      }

}

The output of the code is:

 First object:
 selfCounter=self counter1
 scsf=self counter0

 First object:
 selfCounter=self counter2
 scsf=self counter0

I could understand why in both runs the scsf instance always gets the id assigned to 0 since it is declared to be a final and static field. What confuses me is why the id of "selfCounter" objects gets assigned to be 1 and 2 respectively, I am a bit stuck on how the calculation of id is carried out based on another static instance variable--"count".

Thanks for the guidance.

The ids are 1 and 2 because you're making three SelfCounter objects, all of which share the same count field, which is initialized implicitly to zero.

The first one is the static SelfCounter in WithFinalFields. Its ID is zero because the count field is implicitly initialized to zero, and the value of count++ is zero.

The second ID is one, because the value of count++ is one. And the third ID is then two, because the value of count++ is two.

The variable private static int count; is a static variable, it will have a value of 0 when the program is launched and will not be recreated. private int id=count++; is a dynamic variable.
You have 3 cases when a new instance of the SelfCounter() class is created: 1 because of the line static final SelfCounter scsf=new SelfCounter(); , 1 when the new WithFinalFields() is launched for the first time, and 1 when it is launched for the second time. So, the values during the first and the second launch of WithFinalFields() will be 1 and 2 respectively.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM