My class is implementing a super-class method which which returns List<JComponent>
. The list being returned is read-only:
public abstract class SuperClass {
public abstract List<JComponent> getComponents();
}
In my class, I want to return a field which is declared as List - i.e. a sub-list:
public class SubClass extends SuperClass {
private List<JButton> buttons;
public List<JComponent> getComponents() {
return buttons;
}
}
This generates a compiler error, as List<JButton>
is not a subtype of List<JComponent>
.
I can understand why it doesn't compile, as it shouldn't be allowed to add a JTextField to a List of JButtons.
However, as the list is read-only, then "conceptually" this should be allowed. But, of course, the compiler doesn't know that it is read-only.
Is there any way to achieve what I want to achieve, without changing the method declaration in the super-class, and the field declaration in the sub-class?
Thanks, Calum