0

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.

Nivetha T
  • 481
  • 1
  • 3
  • 17
J.Olufsen
  • 13,415
  • 44
  • 120
  • 185
  • 1
    java does not allow overriding the instance variables. So, you can't do this unless you override calculate method in concrete class. – Bagira Jan 31 '15 at 12:30
  • Java *does* 'allow' overriding the instance variables, it just may not have the effect you want. But it's legal to do so. I don't see what overriding the method has to do with the declaration of the variable. – arcy Jan 31 '15 at 12:41

2 Answers2

1

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.

arcy
  • 12,845
  • 12
  • 58
  • 103
1

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

Paul John
  • 1,626
  • 1
  • 13
  • 15