首页 > 解决方案 > 使用抽象类和 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);
    }
}

非常感谢。

标签: javaabstract-classshapessuper

解决方案


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


推荐阅读