6.7. Static Variables and Methods¶
In Unit 2, we explored the Math
class and its many static methods like
Math.random()
, and we’ve written many main
methods which are always
static. In this lesson, you will learn to write your own static variables and
methods.
Static variables and methods belong to a class and are referenced with the name of the class than an instance of the class, 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.Static methods can be public or private.
The
static
keyword is placed right after the public/private modifier and right before the type of variables and methods in their declarations.
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
System.out.println(ClassName.staticVariable);
ClassName.staticMethod();
Code in static methods only has direct access to other static variables and
static methods. This is because in the body of a static method the special
variable this
is not defined because the static method was not invoked on
any particular instance of the class.
As a consequence code in static methods cannot access any instance variables or
call non-static methods because references to instance variables and methods by
their plain names are implicitly referencing the value of this
. That is in
this class:
public class Student
{
private String name;
public void getName()
{
return name;
}
}
we could also write getName
with an explicit reference to this
:
public void getName()
{
return this.name;
}
But if getName
was static then there would be no this
and thus no way to
access any instances name
variable.
Static methods, however, can access instance methods and call instance method if they somehow have access to an instance of the class, such as having one passed in as an argument:
public class Student
{
private String name;
public Student(String name)
{
this.name = name;
}
public void getName()
{
return name;
}
public static Student copyStudent(Student other)
{
return new Student(other.name);
}
}
In that class copyStudent
is static but the reference to other.name
is
okay because it is on a specific instance of Student
passed as an argument
to the method.
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 also watch how it works in the Java visualizer by clicking the CodeLens button below.
What will the following code print out? Try adding another Person object and see what happens. Try the CodeLens button to run the code step by step.
Another common use for static variables is the keep track of a minimum or maximum value or an average of the values in a collection of objects.
Max Temp: 0
-
maxTemp is changed in each call to the Temperature() constructor.
There is a compiler error because the static variable maxTemp cannot be used inside a non-static constructor.
-
Non-static methods and constructors can use any instance or static variables in the class.
Max Temp: 100
-
Yes, maxTemp is initialized to 0 and then changed to 75 and then 100 by the constructor calls.
Max Temp: 75
-
maxTemp will be changed to 100 by the second constructor call since 100 > 75.
Max Temp: 65
-
maxTemp will not be changed to 65 by the third constructor call because 67 is not > 100.
5-7-2: Consider the class Temperature below which has a static variable. What is the output of the main method below?
public class Temperature
{
private double temperature;
public static double maxTemp = 0;
public Temperature(double temperature)
{
this.temperature = temperature;
if (temperature > maxTemp)
{
maxTemp = temperature;
}
}
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);
}
}
You can see this code in action in the Java visualizer.
Fix the bugs in the following code.
6.7.1.
Programming Challenge : Static Song and counter¶
In the last lesson, we wrote a class with methods to print out the song The Ants Go Marching. Notice that this is a class where there are no instance variables and we don’t really need to generate multiple objects. With students or pets, it makes sense to have multiple objects. With the Song, we can just make the methods static and have just 1 copy of them.
Copy in your class from the last lesson into this active code window. Change the method(s) that print out the verses of the Song to be static. In the main method, change how you call the static methods by using just the classname instead of creating an object.
Add a public static variable called numVerses to the class that keeps track of the number of verses. Increment this variable in the method verse and print it out at the beginning of the verse.
6.7.2. Summary¶
Static methods and variables include the keyword
static
before their name in the header or declaration. They can bepublic
orprivate
.Static variables belong to the class, with all objects of a class sharing a single static variable.
Static methods are associated with the class, not instances of the class.
In static methods, the special variable
this
is not defined.Static variables and methods are referenced with the class name and the dot operator, since they are associated with a class, not objects of a class.
Code in static and non-static methods in a class can refer to static variables and other static methods in the same class with just a simple name.
Static methods cannot access or change the values of instance variables unless they have explicit access to an instance of the class, such as by being passed one as an argument.
Static methods cannot call non-static methods unless they have explicit access to an instance of the class, such as by being passed one as an argument.