0

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

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

4

2 回答 2

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' 方法的多态调用。

于 2013-11-02T18:19:48.043 回答
0

You can remove reportAction() from processFile() and call it separately if likely to change:

// 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);
   }
}
于 2013-11-02T18:20:35.087 回答