我正在尝试获取子类方法以从超类返回变量,但返回值不断给我空返回。我的猜测是我错过了对超类的某种引用。它是从子类方法returnweight()返回值0(零)的值权重。
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
}
}
代码被压缩和翻译(在本文中不是编译器检查的语法) 提前谢谢!
答案 0 :(得分: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 :(得分:2)
您的问题出在您的车辆超类中,构造函数没有做任何事情。
应该是:
public Vehicle(float weight){
this.weight = weight;
}
这将允许您的自行车类(以及任何其他扩展Vehicle的类)通过调用超类的构造函数来实质设置权重;
答案 2 :(得分:1)
提示:您确实正在返回已分配给weight
的唯一值,但是,确实,赋值是隐式的。也许你的意思是在某些时候明确地为它指定一些其他值?也许在施工期间?