Code 1:
public class Ticket {
private int nextSerialNumber = 100;
private int serialNumber ;
public Ticket () {
serialNumber = nextSerialNumber;
nextSerialNumber = nextSerialNumber + 1;
}
public int getSerialNumber () {
return serialNumber ;
}
public static void main( String [ ] args ) {
Ticket t1, t2, t3;
t1 = new Ticket();
t2 = new Ticket();
t3 = new Ticket();
System.out.print( t1.getSerialNumber() + "," );
System.out.print( t2.getSerialNumber() + "," );
System.out.println( t3.getSerialNumber() );
}
}
The code above prints: 100, 100, 100
Code 2:
public class Ticket {
private static int nextSerialNumber = 100;
private static int serialNumber ;
public Ticket () {
serialNumber = nextSerialNumber;
nextSerialNumber = nextSerialNumber + 1;
}
public int getSerialNumber () {
return serialNumber ;
}
public static void main( String [ ] args ) {
Ticket t1, t2, t3;
t1 = new Ticket();
t2 = new Ticket();
t3 = new Ticket();
System.out.print( t1.getSerialNumber() + "," );
System.out.print( t2.getSerialNumber() + "," );
System.out.println( t3.getSerialNumber() );
}
}
The code above prints: 102, 102, 102
Code 3:
public class Ticket {
private static int nextSerialNumber = 100;
private int serialNumber ;
public Ticket () {
serialNumber = nextSerialNumber;
nextSerialNumber = nextSerialNumber + 1;
}
public int getSerialNumber () {
return serialNumber ;
}
public static void main( String [ ] args ) {
Ticket t1, t2, t3;
t1 = new Ticket();
t2 = new Ticket();
t3 = new Ticket();
System.out.print( t1.getSerialNumber() + "," );
System.out.print( t2.getSerialNumber() + "," );
System.out.println( t3.getSerialNumber() );
}
}
The code above prints: 100, 101, 102
My question is why? I know it has to do with the declaration of the static variables, but could someone please clarify as quick as possible?