Static (Lesson-30)

A class has methods and attributes. Any of them can be declared static using the static keyword.
Normally, an attribute is declared like this (as we studied in previous lessons):

public int size;

A static one would look like this:

public static int size;

We are already using a static main method. A static method looks like this:

public static void method(){
    //some code

So what does static do?
When an attribute or method is declared static, it belongs to the class instead of its specific instance instance. A static property is the same for all the objects of a class and is shared by all the objects of the class. When an object is created from a class, it gets a copy of all the non static property but the static property must be shared by all the objects of a class.
Nothing is clear without examples. Let’s create a class and declare a static attribute count in it and see how it is shared by all the objects of the class.
Here is our class:

And here is it’s usage in the main method.

Remember that the static count variable is one for all of the objects if its class. So when any of the objects of the class changes it, it is changed for all of the objects.

The same concept is applied to static methods. Note that static attributes and methods can be accessed even without creating an object of a class. For example, if we declare a static method in our class:

 Let’s access the static method without creating an object of the class:

A static method can be accessed even with the object of the class:

We studied the concept of static. Now let’s see an example of this:
We will create a BankAccount class with all things as usual and a static moneyInBank attribute.

Now let’s use this in the main method:

From the above example, you also got the concept why some variables should be kept private and changed only through get/set methods.

Leave a Comment