Getting duplicate fields when setting from Concrete class

254 Views Asked by At

I need to define constant values in each ConcreteClass that extends AbstractClass. For some reason object ends up having duplicate fields, one set of fields is equal to zeros, next one has proper values.

SomeInterface

public interface SomeInterface{
    double calculate();
} 

AbstractClass

public abstract class AbstractClass implements SomeInterface{
       double x, y;

       public double calculate(){
            return x*y;
       }
    }

ConcreteClass

public class ConcreteClass extends AbstractClass{

    final double x = 1.1;
    public setY(double y){
        this.y = y;
    }

} 

I need my concrete class to store constant value final double x = 1.1; while inheriting the calculate() method implementation from abstract class.

2

There are 2 best solutions below

0
On BEST ANSWER

You have declared x twice, so you get two x variables; one masks the other. It's doing what you told it to.

To have the concrete class set a value, put the setting of it in a (or all) constructor(s) of the ConcreteClass. Don't declare it again.

I don't know a way that you can declare it final and still alter it in a subclass.

0
On

You may be able to do something like this to get around - even though you cannot override instance variables in java.

If all you want to do is have Concrete class's have a constant variable, and the base abstract class use that for calculate method - You could try something like this..

public abstract class AbstractClass implements SomeInterface{

       double x, y;

    public void setX(double x){
        this.x = x;
    }
    public double calculate(){
        return x*y;
   }
}

Then in the concrete class you could still have the final variable and have that passed in to the abstract class's setter.

public class TestAbstractVariable extends TestAbstract {
    {
        final double x = 1.1;
        setX(x);
    }

    public void setY(double y){
        this.y = y;
    }
}

Hope it helps.

Thanks, paul