使用抽象类和super()

时间:2018-12-11 20:32:14

标签: java abstract-class shapes super

我为2d游戏创建了一个抽象形状类,但是两个形状类都出现错误。该错误与super()有关。可能还有其他错误。我还显示了在代码中出现错误的位置。 IS super()适合使用。

形状类

public abstract class Shape {

    int Y;
    int WIDTH;
    int HEIGHT;
    int DIAMETER;

    public Shape(int Y, int WIDTH, int HEIGHT, int DIAMETER) {
        this.Y = Y;
        this.WIDTH = WIDTH;
        this.HEIGHT = HEIGHT;
        this.DIAMETER = DIAMETER;
    }

    public abstract void paint(Graphics g);

}

球拍班

public class Racquet extends Shape {

    int x = 0;
    int xa = 0;
    private Game game;

    public Racquet(int Y, int WIDTH, int HEIGHT) {
        super(Y, WIDTH, HEIGHT); // <- **Error Here**

    }

    public void move() {
        if (x + xa > 0 && x + xa < game.getWidth() - this.WIDTH)
            x = x + xa;
    }

    public void paint(Graphics r) {
        r.setColor(new java.awt.Color(229, 144, 75));
        r.fillRect(x, Y, this.WIDTH, this.HEIGHT);
    }

    public Rectangle getBounds() {
        return new Rectangle(x, this.Y, this.WIDTH, this.HEIGHT);
    }

    public int getTopY() {
        return this.Y - this.HEIGHT;
    }
}

球类

import java.awt.*;

public class Ball extends Shape {

    int x = 0;
    int y = 0;
    int xa = 1;
    int ya = 1;
    private Game game;

    public Ball(Integer DIAMETER) {
        super(DIAMETER); // <- **Error Here**
    }

    void move() {
        if (x + xa < 0)
            xa = game.speed;
        if (x + xa > game.getWidth() - this.DIAMETER)
            xa = -game.speed;
        if (y + ya < 0)
            ya = game.speed;
        if (y + ya > game.getHeight() - this.DIAMETER)
            game.CheckScore();
        if (collision()) {
            ya = -game.speed;
            y = game.racquet.getTopY() - this.DIAMETER;
            game.speed++;
        }
        x = x + xa;
        y = y + ya;

    }

    private boolean collision() {
        return game.racquet.getBounds().intersects(getBounds());
    }

    public void paint(Graphics b) {

        b.setColor(new java.awt.Color(237, 238, 233));
        b.fillOval(x, y, this.DIAMETER, this.DIAMETER);
    }

    public Rectangle getBounds() {
        return new Rectangle(x, y, this.DIAMETER, this.DIAMETER);
    }
}

非常感谢。

3 个答案:

答案 0 :(得分:6)

通过调用super(...),实际上是在调用超类的构造函数。在超类中,只有一个构造函数需要4个参数:Shape(int Y, int WIDTH, int HEIGHT, int DIAMETER),因此您必须在调用super(...)时提供4个参数,或者在超类中提供需要的构造函数,3个参数和1个参数

答案 1 :(得分:1)

您的Shape类没有带有三个参数或一个参数的构造函数。 您可能要使用;

在休闲课中

super(Y, WIDTH, HEIGHT, 0);

在Ball类中

super(0, 0, 0, DIAMETER);

答案 2 :(得分:0)

Shape没有适合您在Racquet和Ball中使用的参数的构造函数。 从“最佳实践”的角度来看,由于在逻辑上应将Ball和Racquet的构造不同,因此最好使用合成而不是继承。