2010-01-29 71 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; 
} 

这将使你的自行车类(和延伸汽车为此事的任何其他类)来调用父类的构造函数基本设置权重;