想象一下以下情况,其中调用超类方法的继承方法必须调用子类的方法:
// 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
答案 0 :(得分:2)
试试这个:
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
方法的多态调用。
答案 1 :(得分:0)
您可以从processFile()中删除reportAction(),如果可能更改则单独调用它:
// super.java
public class Processor {
public void process(String path) {
File file = new File(path);
// some code
// ...
processFile(file);
reportAction(file.name());
}
protected void processFile(File file) {
// some code
// ...
}
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);
reportAction(file.name());
}
}
protected void reportAction(String path) {
System.out.println("batch processing: " + path);
}
}