想象一下以下情况,调用超类方法的继承方法必须调用子类的方法:
// super.java
public class Processor {
public void process(String path) {
File file = new File(path);
// some code
// ...
processFile(file);
}
protected void processFile(File file) {
// some code
// ...
reportAction(file.name());
}
protected void reportAction(String path) {
System.out.println("processing: " + path);
}
}
// child.java
public class BatchProcessor extends Processor {
public void process(String path) {
File folder = new File(path);
File[] contents = folder.listFiles();
int i;
// some code
// ...
for (i = 0; i < contents.length; i++) super.processFile(file);
}
protected void reportAction(String path) {
System.out.println("batch processing: " + path);
}
}
显然,上面显示的代码不能正常工作。类BatchProcessor
打印"processing: <file>"
而不是"batch processing: <file>"
从超类调用方法而不是新方法。有没有办法克服这个障碍?
提前致谢!:D