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.


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;

  public int getNumberOfSides(){
    return TRIANGLE_SIDES;

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

  • Thanks for your response! I will check the FormFactory thing :) But it seems to have to do with swing.. Anyway, I would prefer not using constant then, so I won't have to override a simple getter in all the children of a mother Class. Feb 7 '14 at 13:42
  • The factory pattern (en.wikipedia.org/wiki/Factory_method_pattern) isn't swing specific.
    – ptyx
    Feb 7 '14 at 17:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.