A static method is a method that doesn’t belong to an instance, but to the class itself.  Equivalently a static variable belongs to the class, rather than an object instance.

Let’s take the example of a very simple class

public class Person(){
  private static int population = 0;
  private String name;
  private String surname;

  public Person(String name, String surname){
    population++;
    this.name=name;
    this.surname=surname;
  }

  /**
   * A member variable that returns the specific
   * object's full name.
   */
  public String getFullName(){
    return name+" "+surname;
  }

  /**
   * A static method that returns the total
   * amount of person objects created.
   */
  public static int getPopulation(){
    return population;
  }
}

Ok, above you have 3 variables. One static variable and 2 member variables.

On our constructor method, we initialize the member variables (name and surname) of the newly created object and then, we increment the total amount of persons by 1 via the static population variable.

Even if there are no objects created, we can still ask for the population of the persons without creating anything because “population” is a static variable (it will return 0 population if we haven’t created any object).

We can simply call Person.getPopulation() to retrieve the current population of the Person class…

Then if we create a new object, let’s say, Person pa = new Person(“Ioannis”, “Anifantakis”);
then the population that belongs to the Person class increases to 1.

if we create yet another person, let’s say Person pb = new Person(“Eleni”, “Fragioudaki”); then again we query for the population of the class of persons, rather than some property of pa or pb object.

So since the population refers to all the persons, then we access it directly via a class call (aka Person.population for the variable, and Person.getPopulation() for the method).

Thus, static relates more to procedural programming, that is it creates variables and methods that relate to the total of the class, not to a specific instance (aka a specific object).

Static Variables and Methods vs Member Variables and Methods

Member variables are unique for every created object instance.  That is every person will have a different name and surname.

However, if we increase the population when a person is created, then the static variable “population” will increase.  And since this variable belongs to the total of the persons, it will not be accessed via a specific object, but via the class itself.

So this is why we refer to “Person.population” to access the private population variable since it is a variable that belongs to the Person class as a total.

TL;DR

Static variables and methods belong to the class and they represent a common property that is the same for all the objects, rather than a property that can differ per object.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.