使用抽象类和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);
}
}

非常感谢。

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

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

在recquet类

super(Y, WIDTH, HEIGHT, 0);

球级

super(0, 0, 0, DIAMETER);

Shape没有适合您在Racquet和Ball中使用的参数的构造函数。从"最佳实践"的角度来看,由于Ball和Racquet在逻辑上应该以不同的方式构建,因此使用组合而不是继承可能会更好。

最新更新