java - How to create a collection of different types objects to use it with polymorphis -
i have problem different type of objects in collection, in case arraylist, here there example:
public interface customobject {} public class customobjecta implements customobjects {} public class customobjectb implements customobjects {}
in main call mymethod:
arraylist<customobject> list = new arraylist<>(); for(int i=0; < list.size(); i++) { mymethod(list.get(i)); }
mymethod defined overloading written below:
public void mymethod(customobjecta a) { ... } public void mymethod(customobjectb b) { ... }
there compile-error. how can solve? what's right way (collections, generics, wildcard ?)
one way work around use of visitor pattern, allows attach functionality, without touching domain objects
// visitor, can 'visit' types interface customobjectvisitor { void visita(customobjecta a); void visitb(customobjectb b); } // make customobject visitee public interface customobject { void accept(customobjectvisitor visitor); } // implement classes accept method public class customobjecta implements customobject { @override public void accept(customobjectvisitor visitor) { visitor.visita(this); } } public class customobjectb implements customobject { @override public void accept(customobjectvisitor visitor) { visitor.visitb(this); } }
now can make main
class visitor this:
public class main implements customobjectvisitor { public void methodthatdidntworkbefore() { arraylist<customobject> list = new arraylist<>(); for(customobject obj: list) { obj.accept(this); } } @override public void visita(customobjecta a) { ... } @override public void visitb(customobjectb b) { ... } }
check out wikipedia too, it's useful once wrap head around it.
Comments
Post a Comment