Welcome back!
Here's the promised next lesson! This lesson gets more into things that are language-specific, instead of generic "object oriented" dogma. However, these things are fairly standard across both java, and C++, so they are quite important.
Remember all those times I said that you could only do something in a class, within an instance of that particular class?I lied.
Do you also remember all those veiled references to "static" in lesson one? Yeup. That's the source of the 'corruption' in an otherwise pure language paradigm ;-)
The static declaration for a variable, is rather like the static variable declaration in a C program. It can make a variable be the same, across all instances of a class.
public class cling { static int count=0; public void upcount() { count = count + 1; System.out.println("count is now " + count); } } public class staticcling { public static void main(String args[]) { cling first = new cling(); cling second = new cling(); first.upcount(); second.upcount(); first.upcount(); } }The above example has two classes. The first one is where the strange static variable stuff happens. The second is just a simple callable class. If you call the "main" function of staticcling, it will
And here's its output, when run:
- create two instances of the "cling" class
- call the upcount function of the first instance, to increase its variable count.
- call the upcount function of the second instance, to increase its variable count
- call the upcount function of the second instance, to increase its variable count
But.. shouldn't second.upcount have started at 1?count is now 1 count is now 2 count is now 3Nope. The "static" declaration makes count stick across all instances of the class. A change to count in one instance, shows up in all instances.
But wait.. it gets better.If you define a function as static, then you can call it "directly", without making an instance of the class. This has its benefits, and drawbacks too. The main benefit is the above-mentioned ability to call the function without making a new'd instance. The biggest drawback is that you just broke all the rules about normal variables. Since you don't come from an instance of the class... how does the function know what copy of variables to change?
The bottom line from that, is that static functions can only do the following:
The only exception you might see to the above, is if the function asks to be called with an instance of a class.
- modify variables declared within the same function
- modify static variables for the class
- call other static functions in the class
Some static functions want to be called with an instance of its own class. But that is sort of poor programming. If you were going to do that, you usually may as well just make it a regular member function for that class.