mardi 31 octobre 2017

Polymorphic substitutions with overloaded methods without using instanceof or type checks

I need your advise again. I want to save Objects of Arc and Line in one ArrayList, then get the intersection of both. The question is how can I cast i and j to its original class. I know that instanceof works but that would be the dirtiest method.

public class Intersection {
    public static boolean intersect(ArrayList<Curve> list1, ArrayList<Curve> list2) {
        for (Curve i : list1) {
            for (Curve j : list2) {
                if (i.intersection(j).length > 0) 
                    return true;
            }
        }
        return false;
    }
}

public abstract class Curve {
    public Point[] intersection(Curve c) {
        return new Point[] {};
    }
}

public class Line extends Curve {
    public Point[] intersection(Line l) {
        // returns intersection Point of this and l
    }

    public Point[] intersection(Arc a) {
        // returns intersection Point(s)
    }
}

public class Arc extends Curve {
    public Point[] intersection(Line l) {
        // return intersection Point(s) of this and l
    }

    public Point[] intersection(Arc a) {
        // returns intersection Point(s)
    }
}

Thanks for your help!

Aucun commentaire:

Enregistrer un commentaire