java - polymorphism-like handling of parameters - simple OO? -


i sure must have been asked before cannot seem find similar example. understand polymorphism , method overloading, here seemingly simple scenario solution escapes me:

let's have base class several derived classes. use shapes example

base shape derived circle extends shape derived lineseg extends shape 

etc.

now, shape has method called intersect(other) tests against shape see if intersect. polymorphism easy see how circle, lineseg, etc., can implement own "intersect" methods, and, method overloading, can implement needed combinations. e.g.,

circle.intersect(lineseg) circle.intersect(circle) lineseg.intersect(circle) 

etc.

so far good.

the problem is, if keep central list of shapes, want this:

for shape s foreach shape in shapes   if (s.intersect(shape)) - 

currently, not sure how possible, since method overloading selects "intersect" method match base type shape, , not appropriate parameter type. how can make without if-else chain checking types , down-casting?

btw, using java, not sure language entirely relevant since seems basic design question. seems simple, missing?

thanks!


solved below (thanks!), see details there. basically, having callback in derived classes calls appropriate method (a visitor pattern?), can use "this" keyword invoke proper intersect method, has proper type needed.

my first thought visitor pattern, pretty give every shape 2 methods, 1 i'll call intersect(shape) , 1 dointersect() method per shape type.

it this:

interface shape {     public abstract intersection intersect(shape other);      public abstract intersection dointersect(circle circle);      public abstract intersection dointersect(lineseg line); } class lineseg implements shape {     @override     public intersection intersect(shape other) {         return other.dointersect(this);     }      intersection dointersect(circle circle) {         // code intersect circle     }      intersection dointersect(lineseg other) {        // code intersect lineseg     } }  class circle implements shape {     @override     public intersection intersect(shape other) {         return other.dointersect(this);     }      public intersection dointersect(circle other) {         // code intersect circle     }      public intersection dointersect(lineseg segment) {         // code intersect lineseg     } } 

you might want dointersect methods package private or chose different names these though.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -