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.
1 Answer 1
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.
-
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– leseulsteve2014年02月07日 13:42:28 +00:00Commented Feb 7, 2014 at 13:42
-
The factory pattern (en.wikipedia.org/wiki/Factory_method_pattern) isn't swing specific.ptyx– ptyx2014年02月07日 17:14:02 +00:00Commented Feb 7, 2014 at 17:14