java - 使用抽象类和 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)
,因此您必须在调用时提供 4 个参数super(...)
,或者在超类中提供所需的构造函数,具有 3 个参数和 1 个参数
推荐阅读
- python-3.x - 如何将存储在 Google Drive 中的本地模块导入 Google Collab?
- python - 是否可以从部分 URL 将文件上传到 S3?文件.aa、文件.ab、文件.ac
- node.js - 谷歌云 CPU 分析未显示有用数据
- asp.net-core - 如何在不需要电子邮件确认的情况下更改 ASP.NET Identity 用户的电子邮件?
- javascript - 如何在 Strapi v3 中制作多级(嵌套)类别?
- python - Pandas:过滤以获取包含不在指定列表中的字符的行
- r - 将 R 中的 lm 函数与 foreach 一起用于列表中的每个值
- subprocess - 如果我在事件循环 asyncio 中启动一组要执行的任务,我可以分别对每个任务的返回做出反应吗?
- python - 无法使用通过 sympy.diff 找到的导数函数
- c# - .NET 应用程序来获取 iis 标头和重定向