Static Variables and Methods (Java)
Bola Adebesin
Posted on July 2, 2021
Variables
Static variables are tied to the Class itself. Each object of a class shares the static variable.
Non-static variable (instance variables) are tied to the object. In the example below, every object of the Cat class has its own name variable. However, every object shares the catCount variable.
When you see the static keyword in front of a variable name think of a shared variable.
Class Cat
{
String name; // Non-static variable (each object has it's own copy)
static int catCount; //Static variable (each object of the class Cat shares this variable
Cat(String name){
this.name = name; // Non-static variables can be referenced with "this" keyword
Cat.catCount++; // Static variables are referenced using the class name
}
Methods
Java methods are divided into two categories. Instance methods and Static methods.
Instance Methods
These methods are called on an object and they have access to an objects data (non-static variables). This makes sense. Since an object is an instance of a class, an instance method works on objects.
The reason that instance methods are able to access an objects data is because they have a reference to the object. That reference is stored in the keyword "this". "this" holds a reference that tells us where the object we are referencing is. Without "this" we can't refer to the object.
When you call an instance method, the object that you called the method on is actually passed along to that method as the first argument, we just don't see it.
What we see:
Cat sally = new Cat();
String name = sally.getName();
What is actually happening:
Cat sally = new Cat();
String name = Cat.getName(sally);
The object sally is being passed into the getName method. Then inside the method, the object sally will be referred to as "this".
Static Methods
These methods do not have access to an objects data. Since they don't have an object reference. Static methods don't have "this". Instead a null value is passed to static methods. But, static methods can reference the static variables of the class and other static methods.
Static methods allow us to call a method before we create any objects because they are tied to the class not the object. This is how the main() method works for example.
Posted on July 2, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.