Phils quick-n-dirty intro to object-oriented thinking #2

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.


Static (cling?)

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:
count is now 1
count is now 2
count is now 3
But.. shouldn't second.upcount have started at 1?

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.


static cling gone mad!

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.

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.


C and C++ warning

WARNING to all C and C++ programmers. Apparently, it is NOT possible to define a variable as static, inside a function in java. If you don't know what that means... good. You'll be much happier that way ;-)


Previous section: Getting started with OOP
Next section: When to use OOP


OOP Table of Contents --- phil@bolthole.com
Part of bolthole.com... Solaris tips ... ksh tutorial ... AWK Programming tutorial