有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java子类方法返回零值

我试图得到一个子类方法来从超类返回变量,但是返回值总是给我空的返回。我的猜测是,我遗漏了一些关于超级阶级的东西。它是从子类方法returnweight()返回值0(零)的值weight

 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
    }
}

代码经过压缩和翻译(本文中没有编译器检查的语法) 提前谢谢


共 (2) 个答案

  1. # 1 楼答案

    你有:

    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?
    }
    
  2. # 2 楼答案

    提示:您确实返回了唯一一个赋值给weight的值,尽管这个赋值是隐式的。也许你的意思是在某个时刻显式地给它赋值?也许在施工期间