我正在编写一个具有3个特定类的程序,分别为ImageHandler
,TiffHandler
和JPEGHandler
。JPEGHandler
和TiffHandler
都扩展了ImageHandler
。在这3个类的内部都有一个称为compress()的方法,该方法压缩对象当前正在处理的任何图像。
我也试图创建一个单独的类来实现Runnable,但是我不想创建两个Runnable类,一个用于TiffHandler,一个用于JPEGHandler。我宁愿创建一个可以接受ImageHandler对象的Runnable类。
我的问题是,由于Runnable类仅具有一个ImageHandler对象,因此每当我调用compress()时,它在运行时都会引发错误,说明:
Uncompilable source code - compress() in fjimagecompressor.JPEGHandler cannot override compress() in fjimagecompressor.ImageHandler
overridden method does not throw java.io.IOException
第二行使我感到困惑,因为在ImageHandler中,我有一个称为compress()的空白方法:
public void compress() throws IOException{
/*blank*/
}
在TiffHandler和JPEGHandler的内部,我还具有compress(),它引发IOException,不同之处在于compress()会根据是JPEGHandler还是TiffHandler做一些不同的事情。我不确定我是否只是在错误地使用多态性,还是在我的超类ImageHandler中缺少某些东西。为什么在我确实声明super方法没有声明IOException时,编译器为什么说它没有抛出IOException?
最佳答案
问题可能是您的.class
文件和.java
文件不同步,并且由于可以在throws
中添加ImageHander.java
子句而可以编译,但是您没有更新编译的代码。清理并重新编译您的整个项目,该错误将消失。
关于java - Java多态方法重写,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19487056/