想象一下以下情况,其中调用超类方法的继承方法必须改为调用子类的方法:
// 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
最佳答案
尝试这个 :
Processor processor = new Processor();
processor.process("filePath"); // will print "processing: <file>"
// and
Processor batchProcessor = new BatchProcessor();
batchProcessor.process("filePath"); // will print "batch processing: <file>"
这就是多态方法的工作方式。我想您只是不对子类实例调用
processor
?编辑
请运行以下代码以快速证明自己:
class Parent {
void test() {
subTest();
}
void subTest() {
System.out.println("subTest parent");
}
}
class Child extends Parent {
void subTest() {
System.out.println("subTest Child");
}
public static void main(String... args) {
new Child().test(); // prints "subTest Child"
}
}
在
superClass
实例上调用processFile
subClass
方法时,将发生以下情况:您在整个调用中的
this
引用将引用您的subClass
实例,如果覆盖了它们,则总是导致subClass
方法的多态调用。关于java - 继承的方法可以调用替代方法而不是原始方法吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19745067/