Static Classes In Java

后端 未结 13 1503
慢半拍i
慢半拍i 2020-11-22 07:37

Is there anything like static class in java?

What is the meaning of such a class. Do all the methods of the static class need to be static

13条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 08:26

    Seeing as this is the top result on Google for "static class java" and the best answer isn't here I figured I'd add it. I'm interpreting OP's question as concerning static classes in C#, which are known as singletons in the Java world. For those unaware, in C# the "static" keyword can be applied to a class declaration which means the resulting class can never be instantiated.

    Excerpt from "Effective Java - Second Edition" by Joshua Bloch (widely considered to be one of the best Java style guides available):

    As of release 1.5, there is a third approach to implementing singletons. Simply make an enum type with one element:

    // Enum singleton - the preferred approach
    public enum Elvis {
        INSTANCE;
        public void leaveTheBuilding() { ... }
    }
    

    This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free , and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton. (emphasis author's)

    Bloch, Joshua (2008-05-08). Effective Java (Java Series) (p. 18). Pearson Education.

    I think the implementation and justification are pretty self explanatory.

提交回复
热议问题