Static Classes In Java

后端 未结 13 1555
慢半拍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:25

    All good answers, but I did not saw a reference to java.util.Collections which uses tons of static inner class for their static factor methods. So adding the same.

    Adding an example from java.util.Collections which has multiple static inner class. Inner classes are useful to group code which needs to be accessed via outer class.

    /**
     * @serial include
     */
    static class UnmodifiableSet extends UnmodifiableCollection
                                 implements Set, Serializable {
        private static final long serialVersionUID = -9215047833775013803L;
    
        UnmodifiableSet(Set s)     {super(s);}
        public boolean equals(Object o) {return o == this || c.equals(o);}
        public int hashCode()           {return c.hashCode();}
    }
    

    Here is the static factor method in the java.util.Collections class

    public static  Set unmodifiableSet(Set s) {
        return new UnmodifiableSet<>(s);
    }
    

提交回复
热议问题