Apart from main ()
, the fields and methods we have seen so far have belonged to the objects, or instances of classes. So they are called instance fields and instance methods.
It is also possible to to have fields and methods that belong to the class as a whole. They are therefore called class fields and class methods. The keyword static
is used as a modifier in front of their declarations. We saw it in the case of main ()
: it is not necessary for the JVM to create an instance of a class in order to invoke its main ()
method.
Consider this example:
public class Circle
{ // Fields:
public static final double PI = 3.14159; // Class field
public double radius; // Instance field
// Methods:
public static double area (double r) // Class method: needs the parameter
{
return PI * r * r;
} // area
public double area () // Instance method: uses the field
{
return PI * radius * radius;
} // area
} // Circle
The constant PI does not need to be declared for every object so we make it static. It is used by giving the class name instead of an object name: Circle.PI
. So here are examples of using the Circle class:
double area1 = Circle.PI * 5 * 5;
// static field PI - use class name to refer to it
double area2 = Circle.area (5);
// static method - use class name
// - needs parameters, no object is created
Circle circle = new Circle (5); // Construct object
double area3 = circle.area ();
// non-static method - use object name
// - no parameters, uses object's data (like the Rectangle area in ex7)