Search code examples
javafinal

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.


Solution

  • 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.