Skip to main content

Section 6.7 Static member variables

Suppose that you wanted to write a Student class so that the class could keep track of the number of students it had created. Although you could do this with a global counter variable that is an ugly solution. The right way to do it is to use a static variable. Listing 6.7.1 shows how to do this in Python.
Listing 6.7.1.
Listing 6.7.2 shows how to do this in Java.
Listing 6.7.2.
In Listing 6.7.2, notice that we create a static member variable by using the static modifier on the variable declaration. Once a variable has been declared static in Java it can be accessed from inside the class without prefixing the name of the class as we had to do in Python.
You have attempted of activities on this page.