接口和对象参数的问题

时间:2015-03-10 23:43:30

标签: java interface constructor parameter-passing instance-variables

这是一个难以描述的问题所以我会尽我所能。

基本上我的程序有两个具体的类:MovablePoint和MovableCircle。两者都实现了Movable接口,它有四种方法:moveUp Down left right。

现在我被困住的地方是,当我构建我的MovableCircle时,我需要使用MovablePoint的实例变量来表示圆的中心。但是我还需要MovableCircle的构造函数来接受5个参数:int x,int y,int xSpeed,int ySpeed,int radius。前4个参数是"中心"这个圈子应该由MovablePoint实例化。

这就是我所拥有的:

public class MovableCircle implements Movable {
private int radius;
private int y;
private int x;
private int xSpeed;
private int ySpeed;
public MovablePoint circleCenter;

public MovableCircle (int x, int y, int xSpeed, int ySpeed, int radius) {
    this.radius = radius;
    this.x = circleCenter.getX();
    this.y = circleCenter.getY();
    this.xSpeed = circleCenter.getxSpeed();
    this.ySpeed = circleCenter.getySpeed();
}

如果有帮助,这里也是MovablePoint代码:

public class MovablePoint implements Movable{
private int x;
private int y;
private int xSpeed;
private int ySpeed;

public MovablePoint(int x, int y, int xSpeed, 
        int ySpeed) {
    this.x = x;
    this.y = y;
    this.xSpeed = xSpeed;
    this.ySpeed = ySpeed;
}

显然除了我发布的内容之外还有更多的代码,但我相当肯定我已经正确编写了类方法。我相信我的问题在于我需要使用MovablePoint实例化MovableCircle的中心但我不确定如何补救它。感谢您的帮助,如果这个问题很容易解决,我很抱歉,我只是忘记了......

1 个答案:

答案 0 :(得分:1)

如下:

public class MovableCircle implements Movable {
    private int radius;
    private MovablePoint circleCenter;

    public MovableCircle (int x, int y, int xSpeed, int ySpeed, int radius) {
        this.radius = radius;
        this.circleCenter = new MovablePoint(x, y, xSpeed, ySpeed);
    }