Logout

static - "Class" attributes & methods vs. "Instance" attributes & methods

The Java reserved word "static" indicates that an attribute or method belongs to the class, not to an instance of it.

Though it is not so much a Java term, we can call static attributes and methods "Class attributes and methods". This is as opposed to "Instance attributes and methods".

And, actually, using the terms "class" and "instance" attributes and methods may make more sense than the term "static", but static conveys an important implication, and that is tht there is only one of something that is static. So, for a given application, there is only one main method, for example. Or taking the example of the Math class, which uses, primarily static attributes and methods, there is only one Math.pi attribute, and only one Math.random() method.

That certain attributes and methods are static is actually handy, and saves the bother of having to make an instance of a class to use those certain attriutes and methods. But at the same time, you are limited to having only one "copy" of those attributes or methods. So when deciding whether you should make any given attribute or method static or non-static, you must decide whether it will be used in a "global" way, or whether you will indeed have multiple "copies" or instance of that class active at one time.

The Math Class Example

In fact, Java's Math class is where we have seen class attributes and methods in action already. We have often used Math.random(), and though you may have not noticed, indeed, we are calling the random() method directly from the class, not from an instance of it. We did not go something like Math m = new Math(); and then m.random(). Rather, we just directly went Math.random();.

And the fact that we can go Math.random(), means that random() has been defined as static.

You'll note that if we wanted to we could call static methods from instances of classes we make, but it's bad form, and not advised. So we could go MyClass mc = new MyClass(), and then call a static method, for example, mc.myStaticMethod(), but that implies that the method is static, when actually it is not, and that's not a good idea. In fact, with pre-made Java classes like Math that have all static attributes and methods, the constructor is made private so that you couldn't make an instance of the class even if you wanted.

 

Playing Around with Static ("Class") and Non-static ("Instance") Methods and Attributes

(Do note that the bad habit of calling non-static methods from instances of another class is done above, but only for instructive purposes.)