0

I have these two classes:

class Parent
{ 
   protected static String table;

   public static long getRow()
   {
      String query = "SELECT * FROM " + table + " WHERE id =? " ;
      //other code...
   }
}

I then extend this class :

class Child extends Parent
{
    protected static String table = "tableName";
   //other code..
}

However, when I try to do this:

long id = Child.getRow();

I get an error, because the query is getting "null" put in it where the value of table should be. I.e SELECT * FROM null.

I thought that setting the value of table in the child class would cause it to be updated in the methods it inherits as well, but apparently not. What do I need to do to fix this?

4

4 に答える 4

1

この方法で変数をオーバーライドすることはできません。あなたの例では、各クラスには独自のバージョンのtable変数があり、メソッドが定義されている親ではgetRow、変数は未定義です。使用できるより良いデザインは次のとおりです。

abstract class Parent {

   public abstract String getTable();

   public static long getRow() {
      String query = String.format("SELECT * FROM %s WHERE id = ?", getTable()) ;
      //other code...
   }
}

class Child extends Parent {
    public String getTable() {
        return "tableName";
    }
}
于 2013-02-10T23:13:14.080 に答える
1

インスタンス変数(静的変数も) はnot overridden in your subclass. それらが保護、パブリック、またはデフォルトとしてマークされている場合にのみ、サブクラスで表示されます。ポリモーフィズムと継承はインスタンス変数には適用されません。コードが機能するための唯一のオプションは、 getRow() メソッドを public にして、サブクラスでオーバーライドすることです

于 2013-02-10T23:10:05.017 に答える
0

ネイキッド フィールド アクセスを getter/setter メソッドに置き換えます。

サブクラスで getter/setter をオーバーライドすると、読み書きする変数を制御できるようになります。

Java は、フィールド アクセスに対するこのレベルの制御を提供しません。

于 2013-02-10T23:09:49.590 に答える
0

ちょっとしたこと。メソッド内では、super を使用してシャドー フィールドにアクセスできます。このコードを Child クラスに配置すると、次のようになります。

public void foo() {

    this.table="this belongs to the child";
    super.table="this belongs to the parent";
}

this.table と super.table は異なることに注意してください。いずれにせよ、フィールドをシャドーすることはお勧めできません。

于 2013-02-10T23:16:16.377 に答える