Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();  
   }
}
like image 253
Matthew Washburn Avatar asked Dec 16 '20 14:12

Matthew Washburn


1 Answers

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.

like image 147
SDJ Avatar answered Sep 28 '22 09:09

SDJ