java多态子类functioncall

kiz8lqtg  于 2021-07-05  发布在  Java
关注(0)|答案(1)|浏览(403)

我很肯定我能在stackoverflow上找到这个问题的答案。不幸的是,我不知道这样做的具体提法。
鉴于下面的代码,我有一个问题,我想避免类型检查。这些评论可能比我的话更能说明这一点。
现在我正在尝试建立一个形状系统,其中每个形状都可以与每个可能的特定形状发生碰撞。碰撞等级:

public class ShapeCollision {
    public static boolean intersects(RectShape rectShape1, RectShape rectShape2) { return true; }

    public static boolean intersects(LineShape lineShape, RectShape rectShape) { return true; }

    public static boolean intersects(RectShape rectShape1, Shape shape) { return true; }

    public static boolean intersects(LineShape lineShape, Shape shape) { return true; }

    public static boolean intersects(Shape shape1, Shape shape2){ return true; }
}

形状等级:

public class RectShape extends Shape {
    Vector size;
    public RectShape(Vector pos, Vector size) {
        super(pos);
        this.size = size;
    }
    @Override
    public boolean intersects(IShape shape) {
        return ShapeCollision.intersects(this, shape);
    }
}

public class LineShape extends Shape {
    Vector pos2;
    public LineShape(Vector pos, Vector pos2) {
        super(pos);
        this.pos2 = pos2;
    }
    @Override
    public boolean intersects(IShape shape) {
        return ShapeCollision.intersects(this, shape);
    }
}

public class Shape implements IShape {
    protected Vector pos;
    public Shape(Vector pos) {
        this.pos = pos;
    }
    @Override
    public Vector getPos() {
        return pos;
    }
    @Override
    public void setPos(Vector pos) {
        this.pos = pos;
    }
    @Override
    public void move(Vector movementAmount) {
        pos.add(movementAmount);
    }
    @Override
    public boolean intersects(IShape shape) {
        return ShapeCollision.intersects(this, shape);
    }
}

让我困惑的是:

Shape rect = new RectShape(new Vector(0,0), new Vector(20,20));
Shape rect2 = new RectShape(new Vector(0,0), new Vector(20,20));
Shape line = new LineShape(new Vector(0,0), new Vector(20,20));

//Since I am saving shape and no specific shapetype, it will pass shape and pick the specific superFunction 
//Right now it calls the intersects(RectShape rectShape1, Shape shape) function due to calling it through the shape variable
rect.intersects(rect2); 
//This calls the intersects(LineShape lineShape, Shape shape) function
rect.intersects(line);    
//This calls the intersects(Shape shape1, Shape shape2) function
ShapeCollision.intersects(rect, line);

在不指定变量类型的情况下,如何实现调用带有子类参数的“correct”函数(e、 g.:(线形线形线形矩形)
我不想对这些函数进行任何类型检查,也不想专门调用这些函数,但如果可能的话,可以使用一些designpatters或类似的东西:)

vbkedwbf

vbkedwbf1#

如果不在函数内部进行某种类型检查,或者在将形状示例传递给函数调用之前对其进行显式转换,就无法实现所需的功能。
当然,您可以用特定的类声明对象引用,但我想这并没有真正的帮助。

相关问题