强制子类实现抽象子类
我想在 java 中创建一个抽象类,强制其所有子类实现 SwingWorker
(加上 SwingWorker
的抽象 doInBackground()
和完成())。
在 AbstractClass 中 -
abstract class Task extends SwingWorker<Void, Void>{};
我希望这会导致编译器在扩展类未实现它时抛出异常,但事实并非如此。
我也不太确定如何表明我正在重写这个抽象类。我是否在 ConcreteClass 中重新声明它,如下所示?
class Task extends SwingWorker<Void, Void>{
...
}
或者其他方式?
感谢您的帮助!
I want to create an abstract class in java that forces all its subclasses to implement a SwingWorker
(plus the SwingWorker
's abstract doInBackground()
and done()
).
In AbstractClass -
abstract class Task extends SwingWorker<Void, Void>{};
I would expect this to cause the compiler to throw an exception when an extended class doesn't implement it, but it doesn't.
I am also not quite sure how I would go about indicating that I'm overriding this abstract class. Do I redeclare it in the ConcreteClass as follows?
class Task extends SwingWorker<Void, Void>{
...
}
or some other way?
Thanks for all your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您还需要将这些方法声明为抽象方法,如下所示:
you need to declare the methods also as abstract, like this:
doInBackground() 在 SwingWorker 中是抽象的,因此 Task 的任何具体子类都应该提供一个实现。
然而,done() 在 SwingWorker 中并不是抽象的,因此不需要新的实现。如果你想强制你的子类重新实现它,你需要:
要创建具体的子类,只需扩展 Task 就像扩展任何其他类一样,并使用实现覆盖抽象方法:
doInBackground() is abstract in SwingWorker, so any concrete subclass of Task should have to provide an implementation.
done(), however, is not abstract in SwingWorker, so no new implementation is needed. If you want to force your subclasses to reimplement it you need to:
To create the concrete subclass, just extend Task like you would extend any other class, and override the abstract methods with implementations:
第一段代码将编译,因为类 Task 也被标记为抽象,并且编译器接受它没有实现祖先的抽象成员。但您将无法实例化它(调用 new Task(); )。第二部分不应编译,因为您没有实现抽象方法。要查看示例,请向下滚动此页面:SwingWorker
The first piece of code will compile, because class Task is also marked as abstract and compiler accepts that it doesn't implement abstract members of ancestor. But you will not be able to instantiate it (call new Task(); ). The second piece should not compile, because you didn't implement abstract methods. To see examples scroll down this page: SwingWorker