预先感谢您的回答。 我可能不具备正确形成问题所需的所有知识,但事实是: 我有一堆扩展 Shape 父类(super class)(圆形、矩形、点)的类。 我有一个静态类 Geometry,其方法可以检查不同形状(圆形、矩形、三角形)之间的交集。 在“Geometry”静态类中,我实现了“intersects”方法来接受任何形状组合
public static boolean intersects(Rectangle rect, Point point) {
return rectIntersectsPoint(rect, point);
}
public static boolean intersects(Circle circle, Point point) {
return circleIntersectsPoint(circle, point);
}
public static boolean intersects(Circle circle, Rectangle rect) {
return circleIntersectsRect(circle, rect);
}
每种情况还有更多。 现在,在我的程序中,我有一个方法必须检查交集并且必须接受 Shape 的任何子类:
List<Point> query(Shape shape) {
if (Geo.intersects(this.b, shape)) {
return this.found;
}
......
}
我这样使用它:
Rectangle rect = new Rectangle(10, 10, 200, 300);
found = qt.query(rect );
但是我收到一条错误消息“函数相交需要像(矩形,圆形)这样的参数”。
所以我将一个 Rectangle 对象传递给 query() 方法,并且进展顺利,因为我可以接受“Shape”的任何子类。但是当我在方法中使用它时,它不会保留它的“矩形”类型并成为“形状”对象。
我考虑过为每个子类提供查询方法,但这样我就会一遍又一遍地使用相同的代码。
最佳答案
多态允许您为对象的实际类型调用适当的方法,而不管声明的引用类型如何。
并且双重调度允许您为两种对象类型调用适当的方法。
这是一个草图(未编译或测试):
public abstract class Shape {
public abstract boolean intersects( Shape that );
public abstract boolean intersects(Rectangle that);
public abstract boolean intersects(Circle that);
}
public class Circle extends Shape {
public boolean intersects( Shape that ) {
return that.intersects( this ); // 'this' is of type Circle
}
public boolean intersects( Rectangle that ) { ... }
public boolean intersects( Circle that ) { ... }
}
public class Rectangle extends Shape {
public boolean intersects( Shape that ) {
return that.intersects( this ); // 'this' is of type Rectangle
}
public boolean intersects( Rectangle that ) { ... }
public boolean intersects( Circle that ) { ... }
}
您可以通过定义一对方法中的一个来调用另一个方法,或者让这两个方法调用一个公共(public)实现来避免冗余。前者的一个例子是:
public class Rectangle {
...
public boolean intersects( Circle that ) {
return that.intersects( this );
}
现在,假设您将一个 Circle 和一个 Rectangle 传递给下面的方法。
public boolean intersects( Shape shape1, Shape shape2 ) {
return shape1.intersects( shape2 );
}
在编译时,编译器不知道将调用什么方法。但在运行时,Circle.intersects(Shape)
方法将被调用。它将调用Rectangle.intersects( Circle )
。
关于java - 接受父类(super class)作为参数,但在方法中使用子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54600234/