I apologize in advance if a similar question has been asked before, it's quite complicated to describe correctly what I am looking for, and I will use an example to explain.
We will work with a base class named Shape with the following child classes : Triangle, Square, Pentagon and Hexagon. The 4 last classes represent a shape with 3, 4, 5 and 6 sides respectively. This information "belongs" to the class itself and not to the instance of those classes.
We will also suppose that each class has a static method returning a given color. Every instance of a given class will share the same color.
What I want to do is to call the static function getColor() of my shapes in the ascending order of their number of sides. Meaning, I want to call :
Triangle.getColor()Square.getColor()Pentagon.getColor()Hexagon.getColor()
Unfortunately, I have the following problems (shared by many programming languages)
I can't use Interfaces because the information does not belong to the instances but the classes
I can't define the
getSideCount()static function inside myShapeclass because I would not be able to "override" it in my child classes to get the correct number of sides
I am not asking for a complete code, only for design advices to manage this problem. Maybe I am totally wrong and I should not go this way. Don't hesitate to criticize and suggest a new way to do this.
If you want a more "concrete" example :
I have a string myString.
I have multiple classes A, B, C defining the toString method.
a.toString()returns a string of 1 characterb.toString()returns a string of 2 charactersc.toString()returns a string of 3 characters
myString is the concatenation of a.toString(), b.toString() and c.toString() : ABBCCC.
Tomorrow, I may want that myString is the concatenation of c.toString(), a.toString() and b.toString() : CCCABB. Thus, I defined a static method in the classes A, B and C returning the position of the representation of the instance in myString. What I want to do is to extract in the correct order the representation of my instances.
The "long" way to do this would be :
index ← 0
if( A.position == 1 )
aStr ← extract( myString, index, 1 )
index ← index + 1
elif ( B.position == 1 )
bStr ← extract( myString, index, 2 )
index ← index + 2
elif ( C.position == 1 )
cStr ← extract( myString, index, 3 )
index ← index + 3
endif
if( A.position == 2 )
aStr ← extract( myString, index, 1 )
index ← index + 1
elif ( B.position == 2 )
bStr ← extract( myString, index, 2 )
index ← index + 2
elif ( C.position == 2 )
cStr ← extract( myString, index, 3 )
index ← index + 3
endif
if( A.position == 3 )
aStr ← extract( myString, index, 1 )
index ← index + 1
elif ( B.position == 3 )
bStr ← extract( myString, index, 2 )
index ← index + 2
elif ( C.position == 3 )
cStr ← extract( myString, index, 3 )
index ← index + 3
endif
Thank you in advance for your time and your help.
