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.