Demonstrating the difference between static (class) and instance fields


Classes in Java are represented by objects of the class Class, one object per class.  Consider the following (partial) class:

class Student
   String studentName;
   int studentAge;

   static int numberOfStudents;
   Student s1 = new Student();
   Student s2 = new Student();

While over-simplified, beginners can think of the fields of a class this way: non-static fields are per object.  In the example above, each of the two Student objects has its own set of non-static fields: studentName and studentAge.  So this code will work as expected:

   System.out.println( s1.studentAge );
   System.out.println( s2.studentAge );

However, the Class object representing class Student has no such fields, so the following code is illegal:

   System.out.println( Student.studentAge );  // won't work

Fields declared as static are different.  They are part of the Class object, not the class' objects.  In this example, the field numberofStudents is a field of the obect representing class Student; the two Student objects created above have no such field in them.  This is why you can access static fields this way:

   System.out.println( Student.numberOfStudents );

Because of this, non-static fields, which are per object, are called instance variables.  Static fields, which are per class, are called class variables.

This is an over-simplification of the actual rules of Java.  For example, if the above were true it should be illegal to do this:

   System.out.println( s1.numberOfStudents );

But this in fact will work in Java.  There is still only a single field numberOfStudents no matter how many Student objects exist.  It is however considered a bad practice do to this.