Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 3 down vote accepted

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.

share|improve this answer
    
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. –  leseulsteve Feb 7 at 13:42
    
The factory pattern (en.wikipedia.org/wiki/Factory_method_pattern) isn't swing specific. –  ptyx Feb 7 at 17:14
    
Coooll :) gonna have to check that, thanks again! –  leseulsteve Feb 7 at 17:34

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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