Wednesday, September 24, 2014

The "Static" Keyword

It's taken me some time to wrap my head around the static keyword in Java. Not only that, I keep learning what it does and then forgetting again. So here's my summary, for my own reference and for yours.

This page is called "What is the Static Keyword in Java?" and it explains the word by going over two things: static fields and static methods. (There are also static nested classes--more on those later.)

The page includes what I would call unnecessary info about each of these things, so I've selected and reproduced the truly valuable parts. About static fields, it says:

The value of a static field is the same across all instances of the class. In other words, if a class has a static field named CompanyName, all objects created from the class will have the same value for CompanyName.

About static methods, it says:
Like static fields, static methods are associated with the class itself, not with any particular object created from the class. As a result, you don’t have to create an object from a class before you can use static methods defined by the class.

 Of course, that doesn't entirely cover it, but it does capture a large part of the idea. "Static methods are associated with the class itself, not with any particular object created from the class."  Useful.

Let's break it down a little further and do some side-by-side comparisons.

Non-static fields | Attached to objects (which are instances of classes.) Two objects of the same class can have different values for the same non-static field.

Static fields | Attached to classes. If a class has a static field, all objects of that class have the same value for that field.

Non-static methods | Methods that require the class in which they reside to be instantiated before they can be used.

Static methods | Methods that can be called without creating an object of the type in which they reside (where they're defined.)

---

What becomes clear is that the "static" keyword doesn't seem to have one meaning. It has slightly different meanings in each case, and so each case has to be handled individually.

But wait, there's more. Although "static" cannot be applied to top-level classes (the first thing in your .java file can't be static class myClass), it can be applied to nested classes. (I mentioned these in my previous post, and wow, I'm actually following up on it. #GoMe.)

A nested class is just a class defined within a top-level class. A nested class with the static keyword is known simply as a static nested class. A nested class without the static keyword is called an inner class.

Static nested classes can't refer to non-static fields or methods defined in the top-level class (which I think would be referred to as an outer class, but I'm not sure on that one.) This was giving me problems in an app I was writing, which is what prompted me to learn more on the topic over the last few days.


No comments:

Post a Comment