inheritance - Delegating methods to subclasses in Java -


i have superclass shape, , classes triangle, square, etc. extend shape. have 2 current issues:

  1. my method triangle extends shape not compile. has return shape, not triangle.
  2. 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

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -