Monday, 15 May 2017

Tutorial 8: The Meaning of the static Keyword



So, in the past tutorials, you must have asked yourself what the meaning of the static keyword is. If you haven’t, now is the time to start wondering what static means. I’ll give you some time…


Finished wondering? Great! Because I also wondered what static meant too.


What static does, is it lets you carry operations within a class without having to create an object of the class. When create a static member variable, it means that there will only be one instance or copy of that variable for the entire class because there is only one copy of that class.


Let me give you an example: Let us define a Person class and define a String name and int age as the member variables.

public class Person {

            int age;

            String name;

}

Now, whenever we create a new Person object, each will have its own distinct copy of age and name. In other words, if I create a Person object labeled “brian” and I create another Person object labeled “peter,” I can give “brian” its own age and name. Similarly, I can give “peter” its own age and name.


With static variables, however, there can be only one copy of the variable for the whole class and you cannot define the static variable for each object of the class. So where can we use static in Java? 


Well, one of the most common uses of static in Java is when using counters. Think about it. Let’s say we create a class Person. But as we create a new Person object, we want to keep count of the number of person objects and use this count to give the Person objects an ID. This is what we could do:

public class Person {

            private int id;

            private int name;

            private int age;



            private static int count = 0;

           

            public Person () {

                        id = count;

                        count ++;

            }

           

            public static void main(String[] args) {

                        Person brian = new Person ();

                        Person bob = new Person ();

                        System.out.println(“brian’s id is: ” + brian.id);

                        System.out.println(“bob’s id is: ” + bob.id);

            }
}


Figure 1: This shows one of the commonest uses of static, which is in counting. In this example, the value of the static member variable int count is assigned to the int id member variable and incremented every time a new Person object is created.


There are two ways to assign a value to a static member variable:


Method 1 is illustrated above: private static int count = 0;
Method 2 is where you define the member variable in the main function of the program:
            public static void main (String[] args) {

                        Person.count = 0;

            }

In method 2, you can see that we can also assign the value to the static member variable by calling the class name followed by a dot(.) and then the equals sign and the value as shown above.


If you read the above program line by line, you might have noticed that there is a portion that looks like this:

public Person () {

                        id = count;

                        count ++;

            }

This is what we call a constructor in Java. It is a function that is called every time we create a new object. When we write Person brian = new Person (); the highlighted portion is called and notice that it looks the same as the fragment of code we are discussing above.

You might be asking yourself, why I’ve defined the constructor for the first time ever in this tutorial, yet we have been creating objects just fine in all the past tutorials without having to define the constructor. This is because Java automatically creates a constructor for us when we don’t define one for ourselves.


However, since the constructor is called every time a new object is created, what we are doing is that we are incrementing count every time the constructor is called i.e. whenever a new object is created. Since the counting functionality is not part of the default constructor that Java creates for us, we have to define a custom constructor for ourselves.


When the program is executing, Java will check whether we have defined a custom constructor, and if we have, it will not create a default constructor for us. However, if it checks and finds that we haven’t defined a constructor for our class, it will create a default constructor for us and use it to create the new object.


I will talk about constructors in detail in the next tutorial. I was just writing the above paragraphs to help you understand what is going on. Hope it helps. 


Other than a static member variable such as for counting as described above, you can also have a static function and this also means that it can be called from the class. This means that with a static function, you don’t have to create objects of the class in order to use it.


For example, let’s say that we want to calculate the number of years from 1900 to 2017 and the answer we get, we want to use somewhere else. Or maybe we just want to print the answer to the console. We could write the following:

public class Person {

            int age;

            String name;

            int id;



            public static int yearsSince (int year) {

                        return 2017 – year;

            }

           

            public static void main (String[] args) {

                        System.out.println(“The number of years since 1991 is: ” +

yearsSince(1991));

            }
}


Figure 2: You can even create a static function. Results of the program are on the right.
Try removing the word static from the function and then try to run or save the program. 

Notice that Java will not run the above program because there is no object created for the class. The function should only be called from the class and to do so, it should be declared static.

No comments:

Post a Comment