Tech With Tim Logo
Go back

Static Keyword

Static Keyword

If you've been following along until now you've probably seen the keyword static show up before. Now it's time to talk about what this keyword means!

Static, by definition means not changing and it has a very similar meaning in programming relating to the changing of objects. We can declare both variables and methods as static and I will discuss each below.

Static Variable

A static variable is sometimes called a class variable. This is because it belongs to the class, not an instance of this class. This means that a static variable (or class variable) will be the same for any instance of the class and a change to this variable will be seen in all instances. This is different from instance variables. Remember in our other examples how each of our Dogs would have a different name or age. For a static variable each dog object would see the same value.

To create a static variable (or class variable) we simply add the keyword static after the access modifier.

public class Dog{

    protected static int count = 0;  // class variable

    protected String name; 
    protected int age;

    public Dog(String name, int age){
        this.name = name;
        this.age = age;
        Dog.count += 1;
    }
}

This static variable called count will keep track of how many Dog object we've created. Notice that when we change it we reference the Dog class directly. Again this is because it belongs to the class.

Static Method

When declaring a method as static we are saying that that method has NO access to an instance of the class. Meaning that it can be used by referencing the class name directly and will not be given an object to operate on. This means we cannot access any object variables, attributes or even methods because well we don't have an object to use to access them. Hopefully the example below will help you understand.

To declare a method as static we simply add the static keyword after the access modifier, like so:

public class Dog{

    protected static int count = 0;  // class variable

    protected String name; 
    protected int age;

    public Dog(String name, int age){
        this.name = name;
        this.age = age;
        Dog.count += 1;
    }
    
    // A static method
    public static void display(){
        System.out.println("I am a dog!");
    }
}

Now to call this method we can do use one of the ways shown below.

public class Main{
    public static void main(String[] args){
        Dog d1 = new Dog("tim", 5);

        // These lines both call the static method display
        d1.display(); 
        Dog.display();  // Notice we don't need an instance to call it
    }
}
Design & Development by Ibezio Logo