I have read that I can define a class as static, but I don't understand why I might need to do so. What good are static classes? When might I need to use them? I would appreciate examples.
The static keyword for classes is only allowed for nested classes, inside another class.
The difference between nonstatic nested classes (also known as inner classes) and static nested classes is that objects of the first ones always have a corresponding "outer" object, while objects of the latter ones don't (they only have private-level access, and are inside the namespace).
Here an example:
class Outer {
static class StaticNested {}
class Inner {}
}
Now we can create objects as following:
Outer o = new Outer();
Outer.StaticNested sn = new Outer.StaticNested();
Outer.Inner i = o.new Inner();
o ist the corresponding Outer object to i, while sn has no such element. (Normally you'll create objects of inner classes from methods of the outer objects, there you can simply write new Inner() and it takes this as the outer object.)
From outside of Inner we have no way to get the corresponding outer object, but inside it we can write Outer.this to reference the outer object. This works over several levels, if needed.
You can define an inner class as static like this (to be thorough, the class will become a static nested class) :
class A {
public static class Inner { }
}
This means the class Inner is somehow related to A, but not attached to a particular instance. It is mainly a way to create some sort of relation between the two.
If you're a Java beginner, I suggest you don't lose too much time trying to find some useful application for this. Just remember that this possibility exists, and when you'll have a better understanding of object oriented programming in general and Java in particular, you'll come around this again.
It is important to note that only inner classes can be defined as static, "normal" classes cannot.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With