πŸ““3.7: STATIC Keyword

Table of Contents


πŸ“– This page is a condensed version of CSAwesome Topic 3.7


The static Keyword for Class Variables & Methods

In Unit 1, we explored the Math class and its many static methods like Math.random(), and we’ve always used a main method which is static. In this lesson, you will learn to write your own static variables and static methods.

There is only one copy of a class variable or method for the whole class. For example, the main method is a class (static) method because there should only be 1 main method. If the method is in the same class, you can call it with or without the class name from other static methods in the class: Classname.methodName(); or staticMethodName(); or even with an object of the class: objectName.methodName();.

  • Static variables and methods belong to a class, and are called with the Class name rather than using object variables, like ClassName.methodName();

  • There is only ONE COPY of a static variable or method for the whole class.

    For example, the main method is static because there should only be 1 main method to run your program.

  • Static methods can be public or private.

  • The static keyword is placed right after the access modifier (public or private) and right before the data type of variables and methods in their declarations.
public class ClassName {
     // static variable
     public static type variableName;

     // static method
     public static returnType methodName(parameters) {
           // implementation not shown
     }
}

πŸ“£ To call a static method or variable, use the Class name:

// call a static method or variable
System.out.println(ClassName.staticVariable);
ClassName.staticMethod();

Class Methods

Class methods belong to the class overall, rather than to a specific object of the class. They are called with the class name and the dot operator, like ClassName.methodName();, for example the Math methods like Math.random();.

    // Calling class methods
    // ClassName.methodName();
    int x = Math.sqrt(9);

     // If the method is in the same class,
     // you can call it with or without the class name 
     // from other static methods in the class
     ClassName.methodName();
     methodName();

Let’s revisit the following flowchart to compare three different ways of calling methods. Class (static) methods are called using the class name rather than an individual object’s name:

image

Static methods only have access to other static variables and static methods. Static methods cannot access or change the values of instance variables or the this reference (since there is no calling object for them), and static methods cannot call non-static methods. However, non-static methods have access to all variables (instance or static) and methods (static or non-static) in the class.

Class Variables

Class variables belong to the class, with all objects of a class_ sharing a single copy_ of the class variable. Class variables are designated with the static keyword before the variable type. Class variables that are designated public are accessed outside of the class by using the class name and the dot operator, since they are associated with a class, not objects of a class.

Since there is only 1 copy of a static variable or method, static variables are often used to count how many objects are generated.

In the following class Person, there is a static variable called personCounter that is incremented each time the Person constructor is called to initialize a new Person object. The static method printCounter prints out its value. You can watch how it works in the Java visualizer!

πŸ’¬ DISCUSS: What will the following code print out? Try adding another Person object and see what happens.

Tester method:

// main method for testing
public static void main(String[] args) {
          // call the constructor to create a new person
          Person p1 = new Person("Sana", "sana@gmail.com", "123-456-7890");
          Person p2 = new Person("Jean", "jean@gmail.com", "404 899-9955");

          Person.printPersonCounter();
}

Class definition:

public class Person {
      // instance variables
      private String name;
      private String email;
      private String phoneNumber;

      // static counter variable
      public static int personCounter = 0;

      // static method to print out counter
      public static void printPersonCounter() {
          System.out.println("Person counter: " + personCounter);
      }

      // constructor: construct a Person copying in the data into the instance
      // variables
      public Person(String initName, String initEmail, String initPhone) {
          name = initName;
          email = initEmail;
          phoneNumber = initPhone;
          personCounter++;
      }
}

Another common use for static variables is the keep track of a minimum value, maximum value, or an average of the values in a collection of objects.

Consider the class Temperature below which has a static variable.

πŸ’¬ DISCUSS: What is the output of the main method below? You can see this code in action in the Java visualizer.

Tester method:

public static void main(String[] args) {
               Temperature t1 = new Temperature(75);
               Temperature t2 = new Temperature(100);
               Temperature t3 = new Temperature(65);
               System.out.println("Max Temp: " + Temperature.maxTemp);
}

Class definition:

public class Temperature {
           private double temperature;
           public static double maxTemp = 0;

           public Temperature(double t) {
               temperature = t;
               if (t > maxTemp) {
                    maxTemp = t;
               }
           }
}

The final Keyword for Constant Values

The keyword final can be used in front of a variable declaration to make it a constant value that cannot be modified.

Constant names are traditionally capitalized.

  final double PI = 3.14 ;

⭐️ Summary

  • (AP 3.7.A.1) Class methods cannot access or change the values of instance variables or call instance methods without being passed an instance of the class via a parameter.
  • (AP 3.7.A.2) Class methods can access or change the values of class variables and can call other class methods.
  • (AP 3.7.B.1) Class variables belong to the class, with all objects of a class sharing a single copy of the class variable. Class variables are designated with the static keyword before the variable type.
  • (AP 3.7.B.2) Class variables that are designated public are accessed outside of the class by using the class name and the dot operator, since they are associated with a class, not objects of a class.
  • (AP 3.7.B.3) When a variable is declared final, its value cannot be modified.

Acknowledgement

Content on this page is adapted from Runestone Academy - Barb Ericson, Beryl Hoffman, Peter Seibel.