Static Variables

Static variables and static methods for the layperson.

Static Variables

Consider writing a Planet class that knows the mass of the planet, its radius in meters, and the acceleration due to gravity at the surface of the planet. Those are all instance variables.

Newton’s universal gravitational constant G is something that could be a static variable, also called a class variable. It does not depend on the particular planet, so it can be static.

public class Planet {
  public static final double G = 6.674E-11;
  public double mass, radius, gravity;
  public Planet(double mass, double radius) {
      this.mass = mass; this.radius = radius;
      this.gravity = G*radius/(mass*mass);
  }
}

Of course, actually G is unrelated to the planet at all, so it should probably be in a different class:

public class Physics {
  public static final double G = 6.674E-11;
}

If you look in the source code for java.math, you will see that PI is defined in exactly this way.

Static Methods

A static method is a method that does use any properties (instance variables = non-static variables) of an object in order to work, and can therefore be run knowing only the class, without an actual object.

Examples:

public class MoreMath {
  public static double pythagoras(double a, double b) { return a*a+b*b; }
}
Last modified August 18, 2023: 2022-2023 End State (7352e87)