Why is class declared as static in Java?

29,778

Solution 1

Firstly you cannot make top-level-class static. you can only make a 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 an inner class you can declare static members here.

Can class be nested in nested class?

In a 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 an 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 {

            }
        }   
    }
}

Solution 2

Nested classes (a class within a class) are the only ones that can be declared static. This is so the parent class does not have to be instantiated to access the nested class.

There's some good example code in this answer

Solution 3

It just describes the relation of this class with the containing class.

Inner classes are classes defined within the scope of another class. Instances of inner classes are attached to a specific instance of the container class (the instance in which they were created).

Static nested classes are nested classes, but are defined static. Like static members, they have no relation to a particular instance; they just belong to the containing class. In nested classes, you can't refer to non static members/methods of the containing class, since there's no particular instance associated with them.

Share:
29,778
Al2O3
Author by

Al2O3

Muzzz

Updated on July 26, 2020

Comments

  • Al2O3
    Al2O3 almost 4 years

    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?