Covariant return types in Java enums
Posted
by
Kelvin Chung
on Stack Overflow
See other posts from Stack Overflow
or by Kelvin Chung
Published on 2012-11-10T10:23:56Z
Indexed on
2012/11/10
11:00 UTC
Read the original article
Hit count: 171
As mentioned in another question on this site, something like this is not legal:
public enum MyEnum {
FOO {
public Integer doSomething() { return (Integer) super.doSomething(); }
},
BAR {
public String doSomething() { return (String) super.doSomething(); }
};
public Object doSomething();
}
This is due to covariant return types apparently not working on enum constants (again breaking the illusion that enum constants are singleton subclasses of the enum type...) So, how about we add a bit of generics: is this legal?
public enum MyEnum2 {
FOO {
public Class<Integer> doSomething() { return Integer.class; }
},
BAR {
public Class<String> doSomething() { return String.class; }
};
public Class<?> doSomething();
}
Here, all three return Class
objects, yet the individual constants are "more specific" than the enum type as a whole...
© Stack Overflow or respective owner