Tobias
Tobias

Reputation: 13

Java subclass method returns zero value

I'm trying to to get a subclass method to return the variable from the superclass, however the return value keeps giving me empty returns. My guess would be that i'm missing some kind of reference to the super class. It's the value weight that returns value 0(zero) from the subclass method returnweight().

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

The code is condensed and translated(not compiler-checked syntax in this post) Thanks in advance!

Upvotes: 1

Views: 327

Answers (3)

CheesePls
CheesePls

Reputation: 897

Your issue is in your vehicle superclass, the constructor doesn't do anything.

it should read:

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

This will allow your bike class (and any other class that extends Vehicle for that matter) to essentially set the weight by calling the superclass' constructor;

Upvotes: 2

fastcodejava
fastcodejava

Reputation: 41097

You have :

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

EDIT :

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

Upvotes: 3

Jonathan Feinberg
Jonathan Feinberg

Reputation: 45324

Hint: you are indeed returning the only value that has ever been assigned to weight, although, it's true, that assignment is implicit. Perhaps you mean to explicitly assign some other value to it at some point? Maybe during construction?

Upvotes: 1

Related Questions