[英]Understanding inheritance of class variables
我正在用Java建立一個Challenge24Solver
類。 邏輯本身可以工作並找到預期的解決方案(帶有任意數量的參數)。 無論如何,這些項目的一部分都可以像我期望的那樣工作。
問題來自解決方案表示的問題。 可以公平地說,我已經用Python完成了這個項目,並決定嘗試使用Java作為一種介紹,這可能是問題所在,我也試圖像Python那樣做。
這是我的一些課程:
abstract class Operation { \\ Basic operation class
static String token;
abstract public double operate (double x, double y);
}
class AddOp extends Operation {
static String token = "+";
public double operate (double x, double y) {
return x+y;
}
}
//other operation classes SubOp, MulOp, DivOp
class Challenge24Step { // represents one step in a solution
Operation operator;
double x, y; //operands
double value; //the value of the step (x operator y)
public Challenge24Step (Operation operator, double x, double y) {
this.operator = operator;
// constructor code;
}
public String toString () {
return String.format("%s %s %s = %s", this.x, this.operator.token, this.y,
this.value);
}
}
問題在於它仍然從Operation類獲取令牌:“ null”
我知道這可能是因為operator被聲明為Operation,但我不明白為什么它沒有通過標准繼承:實例,類,每個超類
我將如何重新排列腳本,以便使用更具體的操作類的標記?
靜態變量通過class引用。 您已將operator
定義為Operation
類型,因此operator.token
引用Operation.token
。
我建議為此使用吸氣劑:
abstract Operation { \\ Basic operation class
abstract public double operate (double x, double y);
abstract public String getToken();
}
class AddOp extends Operation {
public double operate (double x, double y) {
return x+y;
}
public String getToken() {
return "+";
}
}
您不能在基類中使token
靜態化,因為那樣,所有繼承的類將只有一個令牌。 您需要使其成為實例變量。 您甚至不能將其放在靜態方法中,因為Java中的static
方法不可覆蓋。
在Java中,變量不可覆蓋。 如果您繼承一個類並添加相同名稱的變量,則派生類中的變量將隱藏 ,而不覆蓋基類中的變量。
要解決此問題,請將token
作為基礎中的abstract
方法,在派生類中提供實現,然后返回所需的值。 如果這樣做,可以用接口替換抽象類,因為其中沒有變量或實現:
interface Operation { // Basic operation class
String getToken();
double operate (double x, double y);
}
class AddOp implements Operation {
public String getToken() {return "+"; }
public double operate (double x, double y) {
return x+y;
}
}
另外,也可以在基數中不分配它,添加一個采用令牌值的構造函數,然后在其中分配它:
abstract class Operation { // Basic operation class
public final String token;
abstract public double operate (double x, double y);
protected Operation(String token) {this.token = token; }
}
class AddOp extends Operation {
public AddOp() { super("+"); }
public double operate (double x, double y) {
return x+y;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.