2016-02-26 71 views
-1

我有一個子類有一個方法,它重寫了父類中的一個方法,但它調用了父類中的方法,而不是子類中的方法。java - 被調用的子類中的覆蓋方法

父類

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

子類

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

它打印出 '*******過程 - 原來的',而不是 '*******過程 - 子' 。我錯過了一些東西,但在代碼中看不到它。

+5

在你的發佈代碼中沒有'extends'(所以沒有子類)?請參閱https://docs.oracle.com/javase/tutorial/java/concepts/inheritance.html – 2016-02-26 10:36:29

+0

附上一些代碼如何調用方法 –

+0

'RecordsCustomer'是'Records'的子類是怎麼樣的? – user2004685

回答

0

確保創建對象並調用它的方法時:

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

而不是:

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

我錯過了這一點。謝謝 – Waz

0

RecordsCustomer類不是子類Record

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"); 
0

如果你打電話如下圖所示(即:真正的對象必須是子類的),那麼它應該工作:

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

注意:安全,測試前做一個乾淨的構建。

0

創建對象是這樣的:

RecordsCustomer myObjectName = new RecordsCustomer(); 

Records myObjectName = new RecordsCustomer(); 

在你的代碼的方法是宣佈他們返回一個字符串數組,但該方法本身並不返回任何東西,你應該返回一個String數組或將de聲明更改爲void