Static methods in Java work on the same basic idea of static functions in other languages like C/C++.
The idea is that sometimes you have a function that either needs to be shared between instances, instead of tied to a specific instance, or to be used without needing to create an object from the class first.
We’ve already seen an instance of this, with our main function.
Creating a Standard Method in Java
If you look at a standard method in java, it would look something like the following:
public void sampleMethod() {
// do stuff
}
When an object is created, it gets it own copy of this method. And typically we want that as it ensure data encapsulation. (Protecting data from be changed in places it shouldn’t. However, it also means that each method makes the memory used go up. In today’s modern computer, we typically don’t worry about that too much.
However, sometimes we don’t want to create an object to use a method. Maybe it’s part of a utility set and the object isn’t needed. A perfect example of this is the main
method. Since the program isn’t running yet, it cannot create an object to run the method, therefore it has to be static.
Creating a Static Method
You just need to add the static keyword after the assessor and before the return type to create a static method.
public static void sampleMethod() {
// do stuff
}
Once you have created the method, you can work within that method like you normally would, with a few minor limitations.
Limitations of Static Methods
There are of course some limitations of static methods. For example, you cannot use an instance variable within your method. That is because the instance variable is unique to the object, where a static method is shared. Therefore you can only use variables in three manners:
- Local variables that are created in the method
- Parameters passed to the method
- Static variables within the object
Another limitation, is very similar. You can only call other static methods, or the methods of an object passed into it. So you cannot call an instance method.
To create a static variable, you will use the same basic process as creating a static method. You simply add the static keyword between assessor and the datatype.
private static int numOfEntities;
Note: that this needs to still be created within the class definition.
Now that a static variable has been created, we can use use it within a static method, for example:
public class Sample1 {
private static int counter = 0;
/*
....
snip
...
*/
public static void updateCounter(int modifier) {
Sample1.counter += modifier;
// notice how we use a parameter to modify a static method.
// This is 2 of the variables that can used within a static method
// also notice how we have to use the class name in front of the static variable
}
}
Static Methods in Java was originally found on Access 2 Learn