To have a variable that is common to all objects, the static modifier needs to be used - these fields are called static fields or class variables. They are associated with the class, rather than an object (or an instance of an object).
Eg in the tutorial example, there should be an ID number unique to each object (ie an instance variable). In order to work out what ID to assign the next Student, you need to keep track of how many Student objects have been created. As this isn't related to any individual object, but the class as a whole.
public class Student
{
private int id;
private String name;
private int age;
private static int numberOfStudents = 1000;
//default constructor
public Student ()
{
id = ++numberOfStudents;
name = "";
age = 0;
}
public static int getNumberOfStudents()
{
return numberOfStudents;
}
...
}
Class variables are referenced by the class name itself - ie Student.numberOfStudents. If you refer to it as student1.numberOfStudents, it's not clear that it's a class variable.
To access the numberOfStudents static field, the accessor needs to be declared as static as well (see above)
I found this to be a very useful explanation: http://download.oracle.com/javase/tutorial/java/javaOO/classvars.html
No comments:
Post a Comment