2010-01-29 68 views
1

我想要獲得一個子類方法來從超類返回變量,但返回值不斷給我空回報。我的猜測是,我錯過了對超類的某種引用。它是從子類方法returnweight()返回值0(零)的值權重。Java子類的方法返回零值

abstract class Vehicle{ 
    protected float weight; 
    public Vehicle(float weight){ 
    } 
    public abstract float returnweight(); 
} 

class Bike extends Vehicle{ 

    public Bike(float weight){ 
     super(weight); 
    } 
    public float returnweight(){ 
     return weight;//This returns as zero no matter what 
    } 
} 

代碼冷凝和翻譯(沒有編譯器檢查在這個崗位語法)提前 謝謝!

回答

3

您有:

public Fordon(float weight) { // What is Fordon? May be Vehicle is needed? 
    // No code here? 
    this.weight = weight; // Forgot this? 
} 

編輯:

public Vehicle(float weight) { 
    // No code here? 
    this.weight = weight; // Forgot this? 
} 
+1

我的壞!錯過了翻譯。 Fordon =車輛。糾正原代碼 – Tobias 2010-01-29 21:43:25

+1

是的,就是這樣!這樣的初學者錯誤。由於超類是抽象的,我只是覺得我會把所有東西都留在空中。非常感謝你的幫助! – Tobias 2010-01-29 21:52:27

1

提示:您確實返回了曾經分配給weight的唯一值,儘管確實是賦值是隱式的。也許你的意思是在某個時候明確地賦予它一些其他的價值?也許在施工期間?

+1

謝謝你的回答!儘管它比我的頭還要大。我不是英語母語,也不是真正的初學者。但我會谷歌與你已經給我:) 原代碼包括更多variabels騎自行車這是爲什麼我使用一個子類 – Tobias 2010-01-29 21:47:56

2

你的問題是在您的車輛超,構造函數什麼都不做。

應改爲:

public Vehicle(float weight){ 
    this.weight = weight; 
} 

這將使你的自行車類(和延伸汽車爲此事的任何其他類)來調用父類的構造函數基本設置權重;