仅适用于某些类的接口?
你能创建一个只能应用于某些类和子类的接口吗?
如果我的接口仅添加到JComponent的不同子类中,并且我需要引用JComponent和我的接口的方法...我应该怎么做?我可以通过将 JComponent 中的方法添加到我的界面来完成此任务。
这看起来很笨拙。有什么更好的方法来做到这一点?
Can you create an interface which can only be applied to certain classes and subclasses?
If my interface is only added to different subclasses of JComponent, and I need to refer to both the methods of JComponent and my interface... how should I do this? Off the top of my head I can accomplish this by adding methods from JComponent to my interface.
This seems clumsy. What is a better way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
显而易见的解决方案是向接口添加一个返回组件的方法(可能是
this
)。或者甚至通用化你的界面:
这不是很好的设计,但它应该可以工作。
The obvious solution is to add a method to your interface that returns the component (which may be
this
).Or even genericise your interface:
It's not great design, but it should work.
在某些情况下,这可能不起作用,但使用泛型可以让您指定多种类型:
如果您希望对象作为非参数化类型上的字段,则可以将类型参数添加到构造函数(这是一个鲜为人知的功能,它绑定了迷惑并给你的同事留下深刻印象):
There might be scenarios where this won't work, but using generics lets you specify several types:
If you want the objects as fields on a non-parametrized type, you add type parameters to the constructor (a little-known feature which is bound to confuse and impress your colleagues):