0

I have an abstract superclass called operation.java and several subclasses extending this class and representing operations. Each such subclass should contain an array of normalizing contants which should be static because it holds globally. I have the following example:

abstract class Operation {

    private static double[] normalizingConstants;

    protected Operation() {
        normalizingConstants = new double[10];
    }
}

class AddOp extends Operation {

    protected AddOp() {
        super();
    }
}

class MinusOp extends Operation {

    protected AddOp() {
        super();
    }
}

Does each subclass hold its own static normalizingConstants? If I call AddOp.normalizingConstants[0] and MinusOp.normalizingConstant[0] I want different results. How can this be achieved?

machinery
  • 5,972
  • 12
  • 67
  • 118
  • Each subclass does not hold its own normalizing constants; but also note that the single instance of `normalizingConstants` is replaced every time you create a new instance of any subclass of `Operation`, because it is assigned in the constructor, not in a static initializer (or direct initialization of the field). – Andy Turner Feb 25 '16 at 11:47
  • Possible duplicate of [What are the rules dictating the inheritance of static variables in Java?](http://stackoverflow.com/questions/9898097/what-are-the-rules-dictating-the-inheritance-of-static-variables-in-java) – Thanga Feb 25 '16 at 12:21

1 Answers1

2

Does each subclass hold its own static normalizingConstants?

No, there is only one normalizingConstants (Operation.normalizingConstants). static fields are tied to the class where they are declared.

If I call AddOp.normalizingConstants[0] and MinusOp.normalizingConstant[0] I want different results. How can this be achieved?

If you need different normalizingConstants arrays, you need to declare another static variable in your sub classes, like

class MinusOp extends Operation {

    private static double[] normalizingConstants;
...

Note that your normalizingConstants fields are only accessible from within the delaring classes since they are declared private.

Also, you should not initialize your static array in the constructor - use a static initializer instead. Otherwise, the array is re-initialized each time you create a new instance of your class (or any sub class).

Andreas Fester
  • 36,091
  • 7
  • 95
  • 123