I have a superclass Shape, and classes Triangle, Square, etc. extend Shape. I have two current issues:
- My method
Triangle extends Shapedoes not compile. It has to return a Shape, not a Triangle. - I want to hide this method. It should only be callable from the Shape superclass.
public class Shape {
public static Shape createShapeFromXML(String xml) {
String type = parse(xml);
if (type.equals("Triangle") {
Triangle.createShapeFromXML(xml);
} else if (...) {
// ...
}
}
}
public class Triangle extends Shape {
public static Triangle createShapeFromXML(String xml) {
....
}
}
public static void main(String[] args) {
String xml = ...
Shape s = Shape.createShapeFromXML(xml);
}
How can I resolve these issues?
why don’t you keep the one static method in the superclass, and have it return the appropriate Shape subclass? The signature would stay the same because Triangles have an is-a relationship to Shape.
You could make the method on the superclass private to get the access restriction you want…
Another approach would be to use the Factory pattern. You could have a ShapeFactory…
This is a good idea because creating the xml parsing is not a concern of the Shape classes. Separate your concerns. The wikipedia link is good at describing the pattern, but you might want a simpler example. See this.