Java – Inheritance and Static Final Variables

finalinheritancejava

I'm a programing student.

I've been having problem to organize Java classes that use inheritance and static final variables.

Let say I have an abstract class named Form that has two children named Rectangle and Triangle. Those two children have a final static variable named NumberOfSides.

Both children classes need identical getters for that variable….

Would it be possible to write that getter in the "mother" class?

Thanks for your help.

Best Answer

This should not be a constant (aka static final).

Given an instance of 'form' (you don't know what class it is), you can call a method 'getNumberOfSides' that will give you what you want. That's a standard method.

You could also consider a factory: FormFactory.createNewFormWithNumberOfSides(n).

Now, you could have something like:

class Triangle implements Form {
  public final static int TRIANGLE_SIDES = 3;

  @Override
  public int getNumberOfSides(){
    return TRIANGLE_SIDES;
  }
}

But avoiding constants (statics) within a hierarchy that shadow each other is a good idea.