2017-09-28 119 views
1

我來自PHP並轉移到java。我問自己(和你們)是否有辦法實現這樣的東西:java - 從父函數/範圍訪問子項屬性

我想實現一個類/類來創建許多數據庫實體的CRUD操作。所有實體繼承其功能 (從父大多數)我需要實現表名idFieldName在父類DatabaseEntity避免編譯器警告。 看起來像java嘗試使用父項屬性(顯然爲空),因爲該函數在父項中實現。

有沒有辦法解決這個問題?任何反饋都非常贊!

abstract class DatabaseEntity { 

    protected String tableName; 
    protected String idFieldName; 

    public DataRecord readFromDB(int recordID) throws SQLException { 

     ... 
     String sqlStatement = String.format("SELECT * FROM %s WHERE %s = %s", this.tableName, this.idFieldName, recordID); // Exception shows this line 
     ... 
    } 
} 

class DatabaseRecord extends DatabaseEntity { 

    protected String tableName = "DatabaseRecordTable"; 
    protected String idFieldName = "ID"; 

    public void getRecord() { 

     ... 
     DataRecord record = this.readFromDB(1); // leads to java.lang.NullPointerException: null 
     ... 
    } 
} 

免責聲明:我是新來的github,我apreciate上improoving我的帖子:)任何反饋

當您使用方法 readFromDB中,你指的是 tableNameidFieldName,這兩個領域

回答

0

保持null只要他們不initailized, 嘗試從抽象類中刪除字段,做這樣的事情:

abstract class DatabaseEntity { 

    // protected String tableName; 
    // protected String idFieldName; 

    public abstract String getTableName(); 



    public abstract String getIdFieldName() ; 

    public DataRecord readFromDB(int recordID) throws SQLException { 

     ... 
     String sqlStatement = String.format("SELECT * FROM %s WHERE %s = %s",getTableName(), getIdFieldName(), recordID); 
     ... 
    } 
} 

和實施將如下所示:

 class DatabaseRecord extends DatabaseEntity { 

    protected String tableName = "DatabaseRecordTable"; 
    protected String idFieldName = "ID"; 

    public void getRecord() throws SQLException { 


     DataRecord record = this.readFromDB(1); 

    } 

    @Override 
    public String getTableName() { 
     return this.tableName; 
    } 

    @Override 
    public String getIdFieldName() { 
     return this.idFieldName ; 
    } 
}