简体   繁体   中英

Does Java not support Covariant Return Types on Enums?

I am trying to implement a factory pattern where users can choose from a defined set of options. To make it easy to store in the database I made the options an enum. Now in one case I need to get the specific implementation back. I was hoping to avoid explicitly instantiating the specific implementation because my factory caches some of the shared dependencies of the things it creates. I assumed I could use covariant return types to accomplish this but it appears they do not work with enums. I'm assuming it is related to how enums can't leverage generic types (which would also solve my problem.) So, does Java not support covariant return types on methods in enums?

public class Scratch
{
   public static class Door  {      }    
   public static class ExteriorDoor extends Door  {  }  
   public interface IDoorFactory  
   {    
      public Door getDoor();
   }

   public enum DoorFactory implements IDoorFactory
   {
       EXTERIOR
       {
          @Override
          public ExteriorDoor getDoor()
          {
             //valid covariant method override
             return new ExteriorDoor(); 
          }
       },
       INTERIOR
       {
          @Override
          public Door getDoor()
          {
            return new Door();
          }
        }
    }  

   public static void main(String[] args)  
   {
    //invalid, method only returns a Door
    ExteriorDoor door = DoorFactory.EXTERIOR.getDoor();  
   }
}

Enum constants are fields, not types. The return type is covariant, but the types of the enumerated constants are anonymous classes. For this reason, the most specific static type for the value returned by getDoor() in your example will be that of Door .

EXTERIOR has type DoorFactory implements IDoorFactory . Hence DoorFactory.EXTERIOR.getDoor() has type Door , not type ExteriorDoor .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM