inheritance - Delegating methods to subclasses in Java -
i have superclass shape, , classes triangle, square, etc. extend shape. have 2 current issues:
- my method
triangle extends shape
not compile. has return shape, not triangle. - i want hide method. should callable 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 resolve these issues?
why don't keep 1 static method in superclass, , have return appropriate shape subclass? signature stay same because triangles have is-a relationship shape.
you make method on superclass private access restriction want...
another approach use factory pattern. have shapefactory... idea because creating xml parsing not concern of shape classes. separate concerns. wikipedia link @ describing pattern, might want simpler example. see this.
Comments
Post a Comment