Java Keywords (Part XVIII): The static keyword

This article summarize the use of the keyword static. I suggest you review Java Keywords (Part V): Classes vs Interfaces and Java Keywords (Part IX): Switch Statements before proceeding.

Java keyword list

abstract continue for new switch
assert default goto* package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const* float native super while
Keyword marked with an asterisk (*) are keywords that, although valid, are not used by programmers.
Very early in this series, I discussed the use of the keyword static and mentioned that I would leave for later discussion another use of that keyword. Well, the time has come.

Using static method in interfaces

Let me start by saying that the only reason why I decided to write a separate, short article for this topic is the same reason for writing the previous article on the use of the default keyword: I didn't want to make the original article on static modifier to be longer than it needed to be. In this specific case, while the use of the keyword is the same in interface methods and class methods, I think it is still a good idea to write this separately.

As you may recall, the primary reason for classes to include static contents is to ensure all instances of the class contain the same data (in the case of static fields) or display identical behavior (in the case of methods). In the case of static interface methods, using the keyword public is not necessary since interface methods are inherently public. So, the code snippet below illustrates a simple example of using the keyword static in an interface method.

public interface FordVehicle {

	static void showBrand() {
You may be wondering why use static interface methods if they accomplish the same as static method in classes? The reason is actually very simple. Packaging static methods in interfaces improves code cohesion by placing related methods in a single location. Like in the case of default methods, you no longer need a class sitting between the interface and implementing classes to accomplish this. Again, this also has the added benefit of simplified class hierarchies.

To learn more, visit the Oracle Java page on interface static methods.

Next up, Part XIX: The assert keyword


Popular posts from this blog

Combining State and Singleton Patterns to Create a State-Machine

Exception Handling: File CRUD Operations Example

The Beauty of the Null Object Pattern