Static Methods
Estimated time to read: 2 minutes
Overview¶
When you declare a method to be static
, it is not allowed to access any instance attributes.
A static
method can be used whether or not an instance of the class has been created.
static
does not have access to this()
nor does it have access to any instances. They are not called via instance.method
they are instead called by class.method
.
When calling a static
method, use the class name by itself: double squareRoot = Math.sqrt(4.2);
System¶
The Java class System
is always used statically.
Since the JRE is always running within a single operating system, there will never be more than one instance of that system.
System
provides a number of important hooks into the OS; the most common being: System.out.println();
Making sense of Static¶
A static
method in a class is accessible without having to create an instance of the object.
For example, if a method is declared as static
within a class, then it can be called from anywhere without having to create the instance first.
Don't do this¶
Ie with the Math class, since the methods within the Math class are mostly statically declared, you don't do this...
Do this¶
You do this instead:
Breaking down main()¶
public static void main (String[]
main()
is a static method within the class which is embedded within it.
Static Method Example¶
Using a previous example, the Math
library in Java has many methods that can be used to work on data that is passed to it.
These are static methods and can be called by using Math.methodName();
Using the example below as our before, we can implement a Math.method to simplify this code further whilst also implementing a static attribute.
public void setSpeed(int newSpeed) {
int maxSpeed = 65;
speed = newSpeed <= maxSpeed ? newSpeed : maxSpeed;
}
Math.min()¶
Using the Math.min() method, we can simplify this down to:
private static final int MAX_SPEED = 65;
public void setSpeed(int newSpeed){
speed = Math.min(newSpeed, MAX_SPEED)
}
Static Imports¶
It is also possible to go one further by importing java.lang.Math.min
into our Class.
I personally do not like this approach as it does not seem that verbose vs specifying the class name each time.