views:

78

answers:

3

Hi! 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!

+1  A: 

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?

Jonathan Feinberg
Thank you for your answer! Altough it's quite a bit over my head. I'm not native english and a real beginner. but i will google away with whhat you have given me :)The original code include more variabels to bike wich is why i use a subclass
Tobias
+3  A: 

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?
}
fastcodejava
My bad! Missed the translation. Fordon=Vehicle. Correct in the original code
Tobias
Yes, thats it! Such a beginner mistake. Since the superclass is abstract i just figured i would leave everything in it empty. Thank you very much for the help!
Tobias
+2  A: 

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;

CheesePls