Skip to main content

Java For Python Programmers Edition 2

Section 6.6 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. In Python, we could do this as follows:
In Java, we would write this same example using a static declaration.
In this example 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.