java - 子类中的重写方法未被调用

java - overriden method in subclass not being called

我有一个子class,它有一个方法,过程覆盖了 parent class 中的方法,但它调用了 parent class,不是子class.

中的那个

Parent class

public class Records {
    protected String[] process(String table, Integer records, String field) throws Exception {
    System.out.println("***************process- original");
    }

    public void insertRecords {
    Records r = new Records()
    String[] records = r.process(table, records, field);
        String record = records[0];
       /* method implementation */
    }
}

子class

public class RecordsCustomer extends Records{
    @Override
    protected String[] process(String table, Integer records, String field) throws Exception {
    System.out.println("***************process- subclass");
}

它打印出“*******process - original”而不是“*******process - subclass”。我遗漏了一些东西,但我在代码中看不到它。

您的 RecordsCustomer class 不属于 class Record class

public class RecordsCustomer extends Records {
    protected String[] process(String table, Integer records, String field) throws Exception {
        System.out.println("***************process- subclass");
    }
}

这样调用,应该能正常工作

Records records = new RecordsCustomer();
records.process("table", 1, "data");

确保在创建对象和调用方法时:

Records records = new RecordsCustomer();
String[] s = records.process(....);

而不是:

Records records = new Records();
String[] s = records.process(....);

如果你调用如下所示(即真正的 object 需要 child class),那么它应该工作:

   Records records = new RecordsCustomer();
   records.process("tableName", 10, "customerName");

注意:为了安全起见,在测试之前做一个干净的构建。

以这种方式创建对象:

RecordsCustomer myObjectName = new RecordsCustomer();

Records myObjectName = new RecordsCustomer();

在您的代码中,您的方法声明它们 return 一个字符串数组,但方法本身没有 return 任何东西,您应该 return 一个字符串数组或更改 de声明 void.