我的类正在实现一个返回的超类方法List<JComponent>.返回的列表是只读的:
public abstract class SuperClass {
public abstract List<JComponent> getComponents();
}
Run Code Online (Sandbox Code Playgroud)
在我的课堂上,我想返回一个声明为List的字段 - 即一个子列表:
public class SubClass extends SuperClass {
private List<JButton> buttons;
public List<JComponent> getComponents() {
return buttons;
}
}
Run Code Online (Sandbox Code Playgroud)
这会生成编译器错误,因为List<JButton>它不是子类型List<JComponent>.
我可以理解它为什么不编译,因为不应该允许将JTextField添加到JButton列表中.
但是,由于列表是只读的,因此应该允许"概念上".但是,当然,编译器不知道它是只读的.
有没有办法实现我想要实现的目标,而无需更改超类中的方法声明,以及子类中的字段声明?
谢谢,卡鲁姆
Ada*_*eld 10
声明getComponents()为:
public List<? extends JComponent> getComponents()
Run Code Online (Sandbox Code Playgroud)
小智 6
我想我找到了我正在寻找的答案......
return Collections.<JComponent>unmodifiableList(buttons);
Run Code Online (Sandbox Code Playgroud)
我曾经尝试过:
return Collections.unmodifiableList(buttons);
Run Code Online (Sandbox Code Playgroud)
但这是类型推断的List<JButton>.
放入显式类型参数允许将List<JButton>其视为a List<JComponent>,这是允许的unmodifiableList().
我现在很开心;-)而且我已经通过讨论学到了一些东西.
Calum
| 归档时间: |
|
| 查看次数: |
8097 次 |
| 最近记录: |