Subscribe to Dogstopper's Code Mania        RSS Feed
-----

Static Methods Explained

Icon 1 Comments
What are static methods, and when should they be used? That is a question I have seen at least twice in the Java forum this week. So, I have taken the liberty of showing you in this lesson. As my primary language is Java, I will demonstrate in that language.

What Are Static Methods?
By definition, static methods are those which have a class scope. What that means is, no matter how many objects are instantiated, based on that single class, that method is shared between all of them. This has many advantages and purposes, as I will show later on. A static method, when called, has the syntax of Classname.methodName(arguments) as opposed to "normal" instance (object) methods where they are called objectName.methodName(arguments). If you're still asking "But what is it?!", you're about to find out.

Here is the non-static version.
class NonStaticExample {

	// This method is static and it determines if two integers are equal
	public boolean isEqual(int a, int b) {
		return a == b;
	}

}

public class Main {
	public static void main(String[] args) {
		// Make two variables to compare
		int a = 1;
		int b = 1;
		
		// Make an object and call its method.
		NonStaticExample nst = new NonStaticExample().
		System.out.println(nst.isEqual(a, b));
	}
}



As seen here, in order to access NonStaticExample's isEqual method, you had to instantiate an object, and then do the appropriate call. However, for simple libraries of functions, like this where methods pretty much only interact with the arguments passed and not so much with object variables, then it would be easier to use a static method. In this way, classes with static methods behave like method libraries instead of objects.

Here is the static version:
class StaticExample {

	// This method is static and it determines if two integers are equal
	public static boolean isEqual(int a, int b) {
		return a == b;
	}

}

public class Main {
	public static void main(String[] args) {
		// Make two variables to compare
		int a = 1;
		int b = 1;
		
		// Just call the method.
		System.out.println(StaticExample.isEqual(a, b));
	}
}



Static methods create class-level methods that can be called from, well, the class. Let me show you another counting script to show how class methods and class variables can be used in sequence to keep track of the number of instances of that object have been created.
class InstanceCounter {

	private static int numOfInstances = 0;

	private static void incCounter() {
		numOfInstances++;
	}

	public void InstanceCounter() {
		InstanceCounter.incCounter();
	}

}

public class Main {
	public static void main(String[] args) {
		ArrayList<InstanceCounter> array = new ArrayList<InstanceCounter>();

		int numOfInstances = (int) (Math.random() * 10);

		for (int i = 0; i < numOfInstances; i++)
			array.add(new InstanceCounter());

		System.out.println(array.size() + " instances created");
	}
}



As you can see, in out main method, we generate a random number of InstanceCounter objects and the class keeps track of it, even though a new object is created. This example further demonstrates what I meant when I said that they are class-level. Objects of the class literally have no sway over the variable, and it is solely the class's responsibility. The static variable is even stored in a different section of the code than the object references are. I hope you have a firm grasp on what a static method and variable is.


When do you use static methods?

Well, as I began to explain earlier, when a class has many related methods, but don't interact with each other, then that class is often a candidate for static methods. If you looks at the Math class as an example, you will see that most if not all of its methods are static. That is because all the methods are related because they're math functions, but they don't interact with each other too much (they do most of their tasks independent from each other).

This library contrasts harshly with a class like a GUI class. The methods of a GUI class almost always depend on each other (like event handling methods and such). A GUI is the perfect example not to "staticify" or make all the methods, variables, etc. static. Often, this is one of the sole causes of many bugs that could have been prevented. Also, in things like games where all the objects work together, it may be better to implement singleton design rather than static methods.

Here is an example of a static method library class. It is called the Math class
public class Math {
	...
	public static double random() {
		// Generate a random number
	}
	
	public static double rint(double a) {
		// Generate a random number
	}
	...
}



See how all the methods are related (because they are math functions), but yet many of the methods can stand by themselves and perform the same task. That is the best example that I could find on this topic and it makes a load of sense to have that extra advantage of grouping all of these stand-alone methods together into a single class.

Another common usage is the singleton method, where the user only allows a single instance of an object to be in existance and a static method retrieves the only instance and returns it to the user:

This is Bill Pugh's solution (a researcher at University of Maryland).
public class Singleton {
	// A private constructor allows no instances from any other class.
	private Singleton() {}
	
	// This class holds the single object
	private static class Holder {
		private static final Singleton OBJECT = new Singleton();
	}
	
	public static Singleton getInstance() {
		return Holder.OBJECT;
	}
}



By using static and private, a class can control the number of instances it can have. That's a more advanced example on usage of static methods, and there are plenty more, but just be careful where they are used.

Thanks for reading
-- Stephen Schwahn

1 Comments On This Entry

Page 1 of 1

erik.price 

09 January 2010 - 11:50 AM
Nice work :^:

I'm bookmarking this since this is such a common question. Now there'll be somewhere to point people to. :)
0
Page 1 of 1

December 2018

S M T W T F S
      1
2345678
91011121314 15
16171819202122
23242526272829
3031     

Recent Entries

Search My Blog

Recent Comments

0 user(s) viewing

0 Guests
0 member(s)
0 anonymous member(s)