Static

In this lesson, we’re going to dive into how to create classes with your own static methods and static variables. To begin, let’s take a quick refresher on static methods. Static methods are methods that belong to an entire class, not a specific object of the class. Static methods are called using the class name and the . operator. We’ve seen a couple of static methods already!

double randomNumber = Math.random();
// Stores a random decimal between 0 and 1 in randomNumber

double number = String.valueOf("2.5");
// Transforms the String "2.5" into a double

In the first example, random() is a static method that belongs to the Math class. We didn’t need to create a Math object (like Math myMathObject = new Math()) in order to use that method. We could just call it using the class name. Similarly, valueOf() is a static method of the String class. Given a String as an input, this method will turn that String into a double. Again, we don’t need to create a String object in order to call this method — we use the class itself to call it. Finally, notice that our main() methods have been static this whole time. When Java runs your program, it calls that the main method of your class — YourClassName.main().

Static Variables

We’ll begin writing our own static methods soon, but before we do, let’s take a look at static variables. Much like static methods, you can think of static variables as belonging to the class itself instead of belonging to a particular object of the class. Just like with static methods, we can access static variables by using the name of the class and the . operator. Finally, we declare static variables by using the static keyword during declaration. This keyword usually comes after the variable’s access modifier (public or private). When we put this all together, we might end up with a class that looks something like this:

public class Dog{

    // Static variables
    public static String genus = "Canis";

    //Instance variables
    public int age;
    public String name;

    public Dog(int inputAge, String inputName){
        this.age = inputAge;
        this.name = inputName;
    }
}

Since all dogs share the same genus, we could use a static variable to store that information for the entire class. However, we want each dog to have it’s own unique name and age, so those aren’t static. We could now access this static variable in a main() function like so:

public class Dog{
    //Variables, constructors and methods defined here

    public static void main(String[] args){
        System.out.println(Dog.genus); // Prints Canis
    }
}

Unlike static methods, you can still access static variables from a specific object of the class. However, no matter what object you use to access the variable, the value will always be the same. You can think of it as all objects of the class sharing the same variable

public static void main(String[] args){
    Dog snoopy = new Dog(3, "Snoopy");
    Dog ringo = new Dog(5, "Ringo");

    System.out.println(Dog.genus); // Prints Canis
    System.out.println(snoopy.genus); // Prints Canis
    System.out.println(ringo.genus); // Prints Canis
}

Finally, you might have seen a few static variables before. If you want easy access to the largest possible integer, you can get it by using Integer.MAXVALUE. If you look at the official documentation you’ll see that this variable is public, static, and final. (final means that you can’t change the variable’s value after creating it.) We’re starting to know a lot of Java keywords!

Modifying Static Variables

Now that we’ve created a couple of static variables, let’s start to edit them. The good news is that editing static variables is similar to editing any other variable. Whether you’re writing code in a constructor, a non-static method, or a static method, you have access to static variables.

Before we jump into the checkpoints, let’s think about times when you might want to edit static variables. Often times, you’ll see static variables used to keep track of information about all objects of a class. For example, our variable numATMs is keeping track of the total number of ATMs in the system. Therefore, every time an ATM is created (using the constructor), we should increase that variable by 1. If we could somehow destroy an ATM, the method that destroys it should decrease numATMs static variable by 1.

Similarly, we have a variable named totalMoney. This variable is keeping track of all money across all ATMs. Whenever we remove money from an ATM using the non-static withdrawMoney() method, we should modify the money instance variable for that particular ATM as well as the totalMoney variable. In doing so, all ATMs will know how much money is in the system.

Writing Your Own Static Methods

Nice work! Now that we’ve seen how static variables work, let’s look into how to write our own static methods.

Let’s get the syntax out of the way first — just like with variables, to create a static method, use the static keyword in the method’s definition. Just like with variables, this keyword usually comes after public or private.

public static void myFirstStaticMethod(){
    // Some code here
}

Often times, you’ll see static methods that are accessors or mutators for static variables.

public static int getMyStaticVariable(){
    return myStaticVariable;
}

public static void setMyStaticVariable(int newValue){
    myStaticVariable = newValue;
}

One important rule to note is that static methods can’t interact with non-static instance variables.

To wrap your mind around this, consider why we use this when working with non-static instance variables. Let’s say we have a Dog class with a non-static instance variable named age. If we have a line of code like this.age = 5;, that means we’re setting the age of a specific Dog equal to 5. However, if age were static, that would mean that the variable belongs to the entire class, not a specific object.

The this keyword can’t be used by a static method since static methods are associated with an entire class, not a specific object of that class. If you try to mix this with a static method, you’ll see the error message non-static variable this cannot be referenced from a static context.

Review

Great work! You now have an understanding of what the static keyword does. In fact, if you’ve made it this far in your Java lessons, you probably have a pretty good sense of what all the keywords and jargon are doing in public static void main(String[] args). Take a moment to celebrate — that line of code can be incredibly intimidating for new learners and it’s a real accomplishment to learn about all of those different pieces.

To review, here are some of the main takeaways about static methods and variables:

  • Static methods and variables are associated with the class as a whole, not objects of the class.
  • Static methods and variables are declared as static by using the static keyword upon declaration.
  • Static methods cannot interact with non-static instance variables. This is due to static methods not having a this reference.
  • Both static methods and non-static methods can interact with static variables.
This page was last updated: not defined. Source