I am new to java. When I was going through language specification I found that static classes cannot be declared, but we can have static inner classes. I am little confused
Because it doesn't add any meaning. 'static' has a meaning when applied to nested classes. It has no meaning on an outer class. So you can't specify it.
A top-level class is by definition already top-level, so there is no point in declaring it static; it is an error to do so.
Static class declarations
AFAIK,if it will allow the top level classes to be declared as static class then it will hold the reference in the heap memory all the time even when you are not using it.and that is what called Memory Leak.so that is why it is restricted to do so.
It is not a restriction, you do not need static class
to define a utility class, you only need static methods
. For example the class Math
in java is full of static methods, but the class itself is not static.
You might only need static class when you define an inner class
that you want to use without creating an instance of the enclosing class, which is allowed in Java.
You can define your utility class as follows:
class Util {
public static void method(){
// your utility method
}
}
static
is a relative term.
static
means "independent of the containing instance". So a static field has the same value, independent of the instance of the class. A static inner class is valid for every instance of the parent class.
But what would a static
top level class be "independent of the containing instance" of? There is no containing instance for a top level class. That's why it cannot be static
(or, it always is static
, depending on your point of view - but in either way, no need to specify it).
Implementation wise, a non-static
inner class contains a reference to the containing outer class. Obviously this difference also is not possible for top level classes.