Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

To declare a static variable, you put them in the class just like instance variables, but you put the keyword static in front. Static variables belong to the class and have one copy. When a value is stored in a static variable, it is not stored in the object of the class. Static variables are useful to keep information that is common to every object.

...

A common example of using static members in a Java class is for utility methods and constants that should be shared across all instances of the class. For instance, let's consider the case of a MathUtility class that contains various mathematical utility methods and constants.

Example 1: Constants

You might have mathematical constants like Pi (π) and Euler's number (e) that don't change and should be the same for all instances. Making them static ensures there's only one copy for all objects, which is memory-efficient.

Code Block
languagejava
public class MathUtility {
    public static final double PI = 3.141592653589793;
    public static final double E = 2.718281828459045;
}

You can then access these without creating an instance of MathUtility:

Code Block
languagejava
double circleArea = MathUtility.PI * radius * radius;

Example 2: Utility Methods

Let's say you often need to calculate the factorial of numbers. Rather than writing this code everywhere you need it, you can encapsulate it in a static method inside a utility class.

Code Block
languagejava
public class MathUtility {
    public static long factorial(int n) {
        long result = 1;
        for (int i = 1; i <= n; i++) {
            result *= i;
        }
        return result;
    }
}

Now, whenever you need to find a factorial, you don't need to create an instance of MathUtility:

Code Block
languagejava
long result = MathUtility.factorial(5);  // Output will be 120

Example 3: Counting Instances

Static members can also be used for counting the number of instances of a class that have been created, which can be useful for debugging or monitoring resource usage.

Code Block
languagejava
public class MyClass {
    private static int instanceCount = 0;

    public MyClass() {
        instanceCount++;
    }

    public static int getInstanceCount() {
        return instanceCount;
    }
}

You can then get the number of instances created without needing an instance of MyClass:

Code Block
languagejava
int instances = MyClass.getInstanceCount();

In summary, static members are useful when you need to share common data or behavior across all instances of a class, rather than replicating that data for each individual instance.

Static Methods

A static method can be accessed by using the name of the class. So you don't need to create an instance to access the method. Methods can also be declared static by placing the static keyword between the access modifier and the method's return type. When a class contains a static method, it is not necessary to create an instance of the class to use the method.

...

However, it's important to be mindful of when and how to use static methods. Overuse of static methods (and static state) can lead to code that is difficult to test and maintain. It's often a good idea to limit use of static methods to cases where you are certain that the method does not need to access or mutate any instance or class-level data.

HeaderClass

Code Block
languagejava
/**
 * Static Header Class
 * 	Class methods for use to generate a program header and footer
 */
public class HeaderClass {
	//variable to keep track of the times one of the class methods was called
	private static int numberTimesUsed = 0; 
	
	//Static Utility to print a header - take a string argument to display
	public static String PrintHeader(String pText)
	{
		String myReturn = "";
		myReturn += PrintLine();
		myReturn += pText + "\n";
		myReturn += PrintLine();	
		numberTimesUsed++; 
		return myReturn;				
	}
	
	//Static Utility to print a footer
	public static String PrintFooter()
	{
		String myReturn = "";
		myReturn += PrintLine();
		myReturn += "End of Program\n";
		myReturn += PrintLine();	
		numberTimesUsed++; 
		return myReturn;	
	}
	
	//Getter to return Utility Method was used 
	public static int getTimesUsed()
	{
		return numberTimesUsed;
	}	
	//Private Methods to use in the class
	//Method prints a line of Characters 
	private static String PrintLine()
	{
		return "######################################\n";
	}

}//end of class

The provided Java class, HeaderClass, consists of static methods that generate a program header and footer. These methods can be called directly from the class itself without creating an instance of it. The class uses a private static integer, numberTimesUsed, to keep track of how many times one of the class methods was called.

  1. numberTimesUsed: This is a private static variable that keeps track of the number of times the header or footer printing methods have been used.

  2. PrintHeader(String pText): This is a static method that takes a String argument pText. It creates a string myReturn composed of a line (obtained from the PrintLine() method), the argument text, and another line. It increments the numberTimesUsed variable by one and returns the constructed string. This is used to print a header with the provided text.

  3. PrintFooter(): This is a static method that creates a string myReturn composed of a line (from the PrintLine() method), the text "End of Program", and another line. It increments the numberTimesUsed variable by one and returns the constructed string. This is used to print a program footer.

  4. getTimesUsed(): This is a static method that returns the current value of numberTimesUsed, providing information on how many times the class's header or footer methods have been used.

  5. PrintLine(): This is a private static method that returns a string of the character '#' repeated 38 times, followed by a newline character. This method is used by PrintHeader and PrintFooter to generate the lines they include in their output.

This class serves as a utility class for providing headers and footers to other parts of a program. Its methods are all static, so they can be called without creating an instance of HeaderClass, and it keeps track of usage with a static counter.