Welcome back!
It's funny.. I didn't really advertise this.. but I'm glad it's being of use. That being said.. 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.
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
But.. shouldn't second.upcount have started at 1?count is now 1 count is now 2 count is now 3
Nope. The "static" declaration makes count stick across all instances of the class. A change to count in one instance, shows up in all instances.
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:
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.
Next section: When to use OOP