Can an enum have abstract methods?

前端 未结 4 648
伪装坚强ぢ
伪装坚强ぢ 2020-12-05 13:11

Can an enum have abstract methods? If so, what is the use, and give a scenario which will illustrate this usage.

4条回答
  •  青春惊慌失措
    2020-12-05 13:27

    Yes, you can define abstract methods in an enum declaration if and only if all enum values have custom class bodies with implementations of those methods (i.e. no concrete enum value may be lacking an implementation).

    public enum Foo {
      BAR {
        public void frobnicate() {
          // do BAR stuff
        }
      },
      BAZ {
        public void frobnicate() {
          // do BAZ stuff
        }
      };
    
      public abstract void frobnicate();
    }
    

提交回复
热议问题