使用重载方法动态调度(运行时多态性)而不使用 instanceof [英] Dynamic dispatch (runtime-polymorphism) with overloaded methods without using instanceof
问题描述
我想将Arc
和Line
的对象保存在一个ArrayList 中,然后得到两者的交集.问题是如何将 i
和 j
转换为原始类.我知道 instanceof
有效,但这将是最脏的方法.
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)
}
}
感谢您的帮助!
推荐答案
由于每个子类已经知道其他子类(例如,Arc
必须知道 Arc
code>Line 类来实现Arc
和Line
相交),使用instanceof
没有错.
Since each sub-class already has to know about the other sub-classes (for example, Arc
must be aware of the Line
class in order to implement Arc
and Line
intersection), there is nothing wrong with using instanceof
.
在每个子类中,您可以覆盖基类的public Point[]intersection(Curve c)
方法并将实现分派给重载方法之一.
In each sub-class you can override the base class's public Point[] intersection(Curve c)
method and dispatch the implementation to one of the overloaded methods.
例如:
public class Arc extends Curve {
@Override
public Point[] intersection(Curve c) {
if (c instanceof Line)
return instersection ((Line) c);
else if (c instanceof Arc)
return intersection ((Arc) c);
else
return an empty array or null, or throw some exception
}
public Point[] intersection(Line l) {
// return intersection Point(s) of this and l
}
public Point[] intersection(Arc a) {
// returns intersection Point(s)
}
}
这样您就不必更改 public static boolean intersect(ArrayList
方法中的任何内容.
This way you don't have to change anything in your public static boolean intersect(ArrayList<Curve> list1, ArrayList<Curve> list2)
method.
这篇关于使用重载方法动态调度(运行时多态性)而不使用 instanceof的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!