我必须为打印出形状的抽象父类创建子类,但每当我尝试创建一个对象时,它一直告诉我我无法实例化一个抽象类,当我abstract从我的代码中删除该关键字时,它会覆盖,它说我也不能这样做.
请帮忙!
我的代码:
public class Rectangle extends VectorObject {
protected int ID, x, y, xlnth, ylnth;
protected int matrix[][];
Rectangle(int id, int ax, int ay, int xlen, int ylen) {
super(id, ax, ay);
xlnth = xlen;
ylnth = ylen;
}
public int getId() {
return ID;
}
public void draw() {
String [][] matrix = new String[20][20];
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 20; j++) {
if (i == x) {
matrix[i][y] = "*";
}
if (j==y) {
matrix[i][y] = "*";
}
System.out.println(matrix[i][y]);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
抽象父类:
abstract class VectorObject {
protected int id, x, y;
VectorObject(int anId, int ax, int ay) {
id = anId;
x = ax;
y = ay;
}
int getId() {
return id;
}
void setNewCoords(int newx, int newy) {
x = newx;
y = newy;
}
public abstract void draw (char [][] matrix);
}
Run Code Online (Sandbox Code Playgroud)
如果这是一个巨大的菜鸟错误,我道歉.我是Java新手.
当你在一个类中定义一个抽象方法时,你会说这个对象的子类必须实现它们,除非它们是另一个抽象类.因此,当您VectorObject使用Rectange类扩展时,必须draw使用相同的参数实现方法.
查看您提供的函数的标题VectorObject:
public abstract void draw ( char [][] matrix );
现在让我们看一下提供的函数的标题Rectange:
public void draw()
这些不一样,因此它不被视为覆盖并且存在错误,因为您尚未实现该方法 draw( char[][] matrix )
实施的正确方法Rectange是:
public class Rectangle extends VectorObject {
//... various methods and variable declarations.
@Override
public void draw( char[][] matrix ) {
//... draw the Rectangle object
}
}
Run Code Online (Sandbox Code Playgroud)
当我们添加@Override注释时,我们告诉编译器我们正在覆盖父类方法.在实现父类方法时,您应该始终使用此批注,因为如果您以某种方式搞砸了签名,它会让您知道,并且其他开发人员更容易理解.
| 归档时间: |
|
| 查看次数: |
11152 次 |
| 最近记录: |