Quick Index
Overview


In Java, most of the methods we code will be instance methods (which we have learned about), because they apply to object instances.

A less used type of method is a "static" method.

There are cases where static methods are useful.

Like the word "static" implies, these methods are fixed/unchanging. Compare that to an instance method like "public int getX()" of a point. Depending on the point object, getX() may return any integer. It is dynamic.

As always, let's look at examples.

Hydraulics Constants Example


In engineering, constants are used to solve problems. Like the name (constant) implies, these values are fixed -- so static methods suit them fine.

Hydraulics Constants
Here is a class that models a hydraulics constants library.

We use static methods to return the fixed values.
/**
 *
 * HydraulicsConstants
 *
 * Library of hydraulics contants
 */

public class HydraulicsConstants {

	public static int squareFeetPerAcre() {
		return 43560;
	}

	public static double convertAcresToSquareFeet(double acres) {
		return acres * HydraulicsConstants.squareFeetPerAcre();
	}

	public static double gallonsPerCubicFoot() {
		return 7.48;
	}

	public static int acresPerSquareMile() {
		return 640;
	}

	public static double convertSquareMilestoAcres(double squareMiles) {
		return squareMiles * HydraulicsConstants.acresPerSquareMile();
	}

	public static double standardAtmosphericPressureAsPoundPerSquareInch() {
		return 14.7;
	}

	public static double gravitationalConstanAsFeetPerSquareSecond() {
		return 32.2;
	}

	public static double waterSpecificWeightAsPoundPerCubicFoot() {
		return 62.3;
	}

}
Hydraulics Constants Driver
Here is an example of using the hydraulics constants library.
	private void sample1()  {
		prn("squareFeetPerAcre: "
			+ HydraulicsConstants.squareFeetPerAcre());
		prn("convertAcresToSquareFeet(2): "
			+ HydraulicsConstants.convertAcresToSquareFeet(2));
		prn("acresPerSquareMile: "
			+ HydraulicsConstants.acresPerSquareMile());
		prn("convertSquareMilestoAcres(3): "
			+ HydraulicsConstants.convertSquareMilestoAcres(3));
	}


Download Example


Example code