Java for Humans {Static Fields & Methods}

Lincoln W Daniel
Jan 7, 2016 · 7 min read
View Table of Contents | Download Supporting Code | Subscribe to ModernNerd Youtube Channel for Coding Videos | By Lincoln W Daniel

We’ve learned that we can create classes to create objects from. Furthermore, an object, or instance of a class, can have instance variables to hold information about itself and methods to manipulate and create more information for users. While not all concepts in Java are objects, most programs in Java revolve around objects.

We can put a good deal of functionality in our classes to organize our code and make remembering what our code does easier. When we have our classes created, we can make objects from them to store information and execute functions we need them to. It’s much like society.

Think of the world like a program. There are seven billion instances of the Human class, perhaps ten billion instances of the AppleTree class, five billion of the Car class, and so on for every object found in nature. There are some Human instances that execute medical functions to keep everyone healthy, some conduct law functions to keep us safe, and some education functions to advance our knowledge. Further, we create instances of the AppleTree class to provide us apples to eat and apple juice to drink, and we need instances of the Car class to get us where we need to go.

If we make an instance of a Car, we can choose its color and customize its speed. If we make an instance of a Human, we get to give it a name, and a unique identification number, and if we make an instance of a AppleTree, we get to choose what color the apples will be. Without instances of these classes, we couldn’t use them to their full potential and customize them as we like. Usually, we want to be able to create objects from our classes to use them in our programs, but sometimes we only need our classes to hold information and perform functions universal to the class itself. In these cases, we don’t need instances of the class to hold the information or run the functions. Such information can be held in static class fields and the functions can be static class methods.

Why Static Fields & Methods Are Important & Useful

The static keyword in Java can be applied to both fields and methods of a class. A field or method of a class that is static can be accessed without an instance of the class. Think of a situation where you want to store information that is the same for everyone and functions that behave the same way for everyone. A great example, again, is the Human class.

A lot of functionalities we, as instances of the Human class, perform are functionalities universal to us all. We all speak, laugh, cry, eat, and walk one step at a time. Because these functions are universal and not specific to any individual, they can be static methods. Further, our governments keep universal information about all of us in order to keep records for the future. They may record information about how many instances of humans exists in the world at any given time, how many are African, North American, Russian, European, Australian, Asian, and so forth. Other universal information may include how many of us are right handed or left handed, how many of us are male or female, and how many of us have a college degree. Such data points are universal and not specific to any one instance of the Human class, so we can store them in static fields.

Static Fields

Because static fields can be accessed without an instance of the class, they are good means of storing information that is universal to a class, such as a count of how many instances of the class have been created. To make a static field, you simply place the static keyword before the declaration of a class’s member variable, or field:

public class Human {
public static int numHumans = 7;
...
}

Once that static field exists, you can access it from outside or inside of the class without an instance of the class. When accessing it, you can simply get or change its value as you wish. The public modifier means that it can be accessed from anywhere in your program that the class can be accessed from. We will learn more about access modifiers soon. Whenever we make a new instance of the Human class, we could have the numHumans static field increased by one so that our whole program knows there’s a new human in town to work with. Because the Human class is public and so is the static field, any part of our program can access that static field by doing the following:

int numHumansInWorld = Human.numHumans;

The way we accessed the field from the class is called dot notation and we will learn more about it in the Methods & Dot Notation chapter.

Static Methods

Classes have three main types of methods: the factory (constructor) method, instance methods, and static methods. A static method of a class can be called without an instance of that class. As a result, static methods don’t have any access to instance variables, or instance fields, because instance variables store information about an instance of a class. Likewise, static methods do not have access to the this keyword in Java because this refers to the current instance of a class, which is not present in the scope of a static method. Further, instance methods of a class cannot be called from static methods of that class because there is no instance of the class present in a static method. However, if an instance of the class is passed to the static method, that instance is free as usual to perform its instance methods in the scope of the static method.

Remember that we use static methods for functionality that is universal to a class. Static methods do not care about instances of the class or their state. If we have an instance of our Human class, we can call a method to make it change its name or speak its name. However, if we only want to use our Human class to run some calculations to determine the DNA of a human or to check how many humans currently exist in the world, we can make static methods to do that. Let’s try the latter:

public class Human {
private static int numHumans = 0;
public Human(String name){
this.name = name;
numHumans++;
}

public static int getNumHumans(){
return numHumans;
}
...
}

If we want to access the static numHumans field of the Human class from outside of the Human class this time, we must call the getNumHumans() method because we made the static field private by using the private access modifier, which means the field can only be accessed from within the class its a member of, or belongs to. This is usually a wise design pattern to ensure that your fields are only being used how we want; the numHumans field in our Human class can only be changed from within the class and accessed through the getNumHumans() static method. We can call the static method from outside or inside the Human class because it is public, and it will return to us the value of the static field holding the number of Human instances that exist in our program:

int numHumansInWorld = Human.getNumHumans();

That will return the value of the static numHumans field in the Human class and store it in the local numHumansInWorld variable for later use.

Finally, instances of a class can call the public static methods of that class from anywhere in the program, but an instance of a class can only call its private static methods, like any other private method, from within the class. If we have a static method that simply serves to increment the static numHumans field in our Human class by one and return the new value each time it is called, it’d be best to have that declared as a private method so that it can only be called within the Human class either by instances of the Human class or from other static methods:

public class Human {
private static int numHumans = 0;
private String name = name;
... public Human(String name){
this.name = name;
incrementNumHumansAndPrint();
}
private static int incrementNumHumans(){
return numHumans = numHumans + 1;
}
private static void incrementNumHumansAndPrint(){
System.out.println("There are now "
+ incrementNumHumans() + " Human instances in society.");
}
...
}

Now when we call the constructor method of our Human class to create a new instance of it, the constructor will set the name of our instance with whatever we provide it and finish by calling the private and static incrementNumHumansAndPrint() method of the Human class to print the new number of Human instances that exist in our program. Notice the the incrementNumHumansAndPrint() method calls on the private and static incrementNumHumans() method to do the work of increasing the number of humans by one. These functions may appear trivial and lazy now, but we’ll soon see why its smart to separate work like this.

public static main(String[] args) {
Human newHuman = new Human("ModernNerd");
/*creates a new Human instance
and prints "There are now 1 Human instances in society."*/
}

ModernNerd Code

Learn to Code Life. Subscribe to Video Tutorials on Youtube

Lincoln W Daniel

Written by

My passion is in developing software to enable people to accomplish their goals more efficiently. Author @JavaForHumans.com. Creator of @Smedian.com

ModernNerd Code

Learn to Code Life. Subscribe to Video Tutorials on Youtube

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade