0

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?

2
Contributors
1
Reply
2
Views
5 Years
Discussion Span
Last Post by stultuske
0

static: class scope. instance variable: instance scope.

if it's not a static variable, it's an instance variable. they can only be reached through an instance of the class, so can only be accessed if an instance is created.

if you set the value for an instance variable, you set it for that instance only.
a static variable is for the class itself. you don't need to create an instance to use/access the variable. yes, you can set the variable both through the class or through an instance, but, instead of instance variables, which are 'copied' each time an instance is created, there is only one 'version' of each static variable or method. if you overwrite it for the class or for one instance, you overwrite the value for all instances.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.