1

I am Testing Program with a number of nested static classes.

public class Q 
{
    static class A {

        static class B{

            static class C{

                static class D{

                    static class E{

                    }
                }
            } 
        }
    }


    class C{

        class D{

            class F{

            }
        }

        static class E{
    }
}

}

But here i cant declare static class E second time .Which shows error "static modifier not allowed here". Whats wrong with me? Don't shout me. I know its a bad practice .But I have the curiosity to know the reason.

Roman C
  • 49,761
  • 33
  • 66
  • 176
RAJIL KV
  • 399
  • 1
  • 7
  • 24

2 Answers2

4

You can simplify all that code down to just:

class C{

    static class E{
    }
}

So the question becomes why can a static inner class not be created within a non-static inner class.

This is answered here:

Why a non-static inner-class cannot have static members (fields and methods)?

The entire body of a Non-static inner class is Not within a static scope, and therefore you can't have static members in there.

Community
  • 1
  • 1
Tim B
  • 40,716
  • 16
  • 83
  • 128
1
  class C{

        class D{

            class F{

            }
        }

        static class E{
    }
}

If you take a close look at the nested inner classes above, you are trying to put static nested class within a non-static inner class, which is not permitted in java.

Ankur Shanbhag
  • 7,746
  • 2
  • 28
  • 38