How to set abstract class variable?

Is it possible to set abstract class variable with default value of class which extends abstract class? I mean if I have abstract class Atrakcja:

public abstract class Atrakcja implements ElementWycieczki{
    private double time;
    public Atrakcja(double time)
    {
        this.time = time;
    }
}

I want to set time variable by default value from

public class DrewnianaCerkiew extends Atrakcja{
    private double time = 0.5;
    public DrewnianaCerkiew(){
            ...
    }
}

I know that if i would like to put parameter to constructor it would be easy, just put parameter to DrewnianaCerkiew constructor, then super(param) and it would set time. But in some classes which extends Atrakcja (abstract class) want to set default time.

One of solution what I want is to do is just: super(0.5);, but is there another way to make default value for class? It would be better if I can set default value to variable of class e.g. double time = 0.5; then super(time) but it doesn’t work.

Answer

It is only possible if you assign the variable in the base class’ constructor:

public abstract class Atrakcja implements ElementWycieczki {
    private double time;
    public Atrakcja(double time) {
        this.time = time;
    }
}

public class DrewnianaCerkiew extends Atrakcja {
    public DrewnianaCerkiew() {
            super(0.5d);
    }
}

Adding a new field time to class DrewnianaCerkiew creates a new member which is not connected in any way to the field in the base class. Don’t do it, it is confusing.

If all you are looking for is having all “defaults” at the top of the class definition (and not inlined in the super constructor call), you can extract them to a constant:

public class DrewnianaCerkiew extends Atrakcja {
    private static final double DEFAULT_TIME = 0.5d;
    public DrewnianaCerkiew() {
            super(DEFAULT_TIME);
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *