Why there is no static class in Java

前端 未结 5 813
死守一世寂寞
死守一世寂寞 2021-01-14 16:52

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

相关标签:
5条回答
  • 2021-01-14 17:41

    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.

    0 讨论(0)
  • 2021-01-14 17:47

    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

    0 讨论(0)
  • 2021-01-14 17:47

    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.

    0 讨论(0)
  • 2021-01-14 17:51

    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
      }
    }
    
    0 讨论(0)
  • 2021-01-14 17:54

    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.

    0 讨论(0)
提交回复
热议问题