继承的方法可以调用覆盖方法而不是原始方法吗?

时间:2013-11-02 18:06:27

标签: java inheritance override

想象一下以下情况,其中调用超类方法的继承方法必须调用子类的方法:

// 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

2 个答案:

答案 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);
   }
}