User3
User3

Reputation: 2535

Extending a class and handling a final variable in multiple constructors

I am trying to extend a class to have a slight variation in implementation. Now there is a final variable in this parent class as:

private final float mIndicatorItemLength = DP * 4;

defined at the class level and I want to supply a custom value to this variable from my child class. As this variable is final I am changing it to be initialized from the constructor. I have two constructors here:

public HorizontalCirclePagerIndicatorDecoration()

referenced as:

public HorizontalCirclePagerIndicatorDecoration() {
    mIndicatorItemLength = DP * 4;
}

and

public HorizontalCirclePagerIndicatorDecoration(int colorActive, int colorInactive, int mIndicatorItemLength)

The first constructor is default, the second one I want to access from my child class and set custom values using the super keyword from the child class like:

public TPagerIndicator(int colorActive, int colorInactive) {
    super(colorActive, colorInactive, mIndicatorItemLength);
}

My child class signature being like:

TPagerIndicator extends HorizontalCirclePagerIndicatorDecoration

However I am getting an error here as: Cannot reference TPagerIndicator.mIndicatorItemLength before supertype constructor has been called.

Now I think I will have to remove the final modifier on the

private final float mIndicatorItemLength = DP * 4;

in the parent class. Is this the right way to go?

Upvotes: 0

Views: 259

Answers (1)

LppEdd
LppEdd

Reputation: 21172

This would be the correct approach. As you know, the subclass must at least call one superclass constructor. Using a final property which is still not initialized (mIndicatorItemLength) is not permitted in Java.

class HorizontalCirclePagerIndicatorDecoration {
   ...
   private final float mIndicatorItemLength;

   HorizontalCirclePagerIndicatorDecoration() {
      mIndicatorItemLength = DP * 4;
   }

   HorizontalCirclePagerIndicatorDecoration(
         final int colorActive, 
         final int colorInactive, 
         final int mIndicatorItemLength) {
      ...
      this.mIndicatorItemLength = mIndicatorItemLength;
   }

   ...
} 

class TPagerIndicator extends HorizontalCirclePagerIndicatorDecoration {
   TPagerIndicator(
         final int colorActive,
         final int colorInactive) {
      super(colorActive, colorInactive, 12.3F /* Explicit set */);
   }

   TPagerIndicator(
         final int colorActive,
         final int colorInactive
         final int mIndicatorItemLength) {
      super(colorActive, colorInactive, mIndicatorItemLength /* Input set */);
   }

   ...
}

Upvotes: 1

Related Questions