Al2O3 Al2O3 - 1 month ago 8
Java Question

Why is class declared as static in Java?

I've seen class been declared as

static
in
java
, but confused:

Since class is used to create objects, and different objects have different memory allocations.

Then what is
"static"
used for when declaring a class?Does it mean the
member variables
are all
static
?

Does this make sense?

Answer Source

Firstly you cannot make top-level-class static. you can only make an nested class static. By making an nested class static you basically are saying that you don't need an instance of the nested class to use it from your outer class/top-level-class.

Example:

class Outer {

static class nestedStaticClass {

//its member variables and methods (don't nessarily need to be static)
//but cannot access members of the enclosing class
}

public void OuterMethod(){
//can access members of nestedStaticClass w/o an instance
}
}

Also to add, it is illegal to declare static fields inside an inner class unless they are constants (in other words, static final). As a static nested class isn't considered an inner class you can declare static members here.

Can class be nested in nested class?

In single word, yes. Look at the below Test, both nested (Inner classes) and nested static class can have nested classes in 'em. But remember you can only declare a static class inside a top-level class, it is illegal to declare it inside a nested inner class.

public class Test {
    public class Inner1 {
        public class Inner2 {
            public class Inner3 {

            }
        }
    }
    public static class nested1 {
        public static class nested2 {
            public static class nested3 {

            }
        }   
    }
}