Why can I anonymously subclass an enum but not a final class?

前端 未结 3 1611
说谎
说谎 2021-01-11 15:43

This code:

public class Sandbox {
    public enum E {
        VALUE {
            @Override
            public String toString() {
                return \"I         


        
3条回答
  •  悲&欢浪女
    2021-01-11 16:46

    I think if you compare classes and enums, then the enum E can be compared to a class, and the enum value VALUE can be compared to an anonymous instance. Thus, your first example can be rewritten as following:

    public class Sandbox {
        public static class E {
            public static final E VALUE = new E() {
                @Override
                public String toString() {
                    return "I'm the value";
                }
            };
    
            @Override
            public String toString() {
               return "I'm the enum";
           }
        }
        public static void main(String[] args) {
            System.out.println(E.VALUE);
        }
    }
    

提交回复
热议问题