I have 3 different type of shape diagrams say Rectangle, Cube, Circle, I want to define classes for them such that
-
All classes would have Title & Color property/method,
-
Circle & Rectangle would have additional method Area,
-
Similarly Cube would have Volume method rather than Area method.
There is a method in which I get the reference of of ‘object’, following is sample method
public void ShapeClicked(object obj)
{
// Check the type of obj & type cast it accordingly & call the method on that object
object obj = new Circle();
if (obj is Circle)
{
Circle circleObj = (Circle)obj;
circleObj.GetArea();
}
else if (obj is Rectangle)
{
Rectangle rectangleObj = (Rectangle)obj;
rectangleObj.GetArea();
}
else if (obj is Cube)
{
Cube cubeObj = (Cube)obj;
cubeObj.GetVolume();
}
}
How can I design my classes such that in ‘ShapeClicked(object obj)’ method
-
a) I need not to check the type every time (should happen at run time), (This is important for me because I have many methods like ‘ShapeClicked’ which requires me checking the type)
-
b) if object is of Circle then it would get only Area method, similarly for Cube object it would get only Volume method.
I can think of two approaches
-
Put all the methods & properties in base class & only override required methods in derive class. Create a Factory method/class which would return the reference of Base class. With this approach my ‘b’ requirement does not meet
-
Put only common methods/property (like color) in base class & add additional methods in derive class. This does not solve #a 🙁
Can anybody suggest me some solution which solves both #a & #b
Introduce a new interface.
Update
Your method would look like: