我试图为矩形和椭圆创建一个抽象形状类,我给形状类唯一的抽象方法是draw方法,但在我为其添加构造函数和其他内容后,代码中的矩形类出现错误,说颜色和其他变量在此处具有私有访问权限,这是我的代码:
public abstract class Shape{
private int x, y, width, height;
private Color color;
public Shape(int x, int y, int width, int height, Color color){
setXY(x, y);
setSize(width, height);
setColor(color);
}
public boolean setXY(int x, int y){
this.x=x;
this.y=y;
return true;
}
public boolean setSize(int width, int height){
this.width=width;
this.height=height;
return true;
}
public boolean setColor(Color color){
if(color==null)
return false;
this.color=color;
return true;
}
public abstract void draw(Graphics g);
}
class Rectangle extends Shape{
public Rectangle(int x, int y, int width, int height, Color color){
super(x, y, width, height, color);
}
public void draw(Graphics g){
setColor(color);
fillRect(x, y, width, height);
setColor(Color.BLACK);
drawRect(x, y, width, height);
}
}
class Ellipse extends Shape{
public Ellipse(int x, int y, int width, int height, Color color){
super(x, y, width, height, color);
}
public void draw(Graphics g){
g.setColor(color);
g.fillOval(x, y, width, height);
g.setColor(Color.BLACK);
g.drawOval(x, y, width, height);
}
}
public int getX(){return this.x;}
等等... 然后在子类(例如Ellipse
)中使用它们,如:g.fillOval(getX(), getY(), getWidth(), getHeight());
- Totòpublic int getWidth(){return this.width;}public int getX(){return this.x;}
),并使用它们来检索字段值,而不是直接访问字段。 - Totòtrue
?setSomething
不需要返回任何内容,而getSomeField
必须返回someField
。如果您可以使用最新更改更新问题中的代码,我们可能能够提供帮助。 - Totò