【发布时间】:2015-04-20 01:16:28
【问题描述】:
我正在学习多态性并遇到一些问题。我基本上应该制作一个“屏幕保护程序”,其中包含不同的图像移动和弹跳。我使用四个子类型 Square、Star、Circle 和 Triangle 的数组来实现这一点,但是我一次只能拥有一个类的一个实例(当我单击时,它会生成一个新形状而旧的形状会消失)。
我尝试过制作这样的数组列表:
public void mouseClicked(MouseEvent e) {
if (i < 3) {
i += 1;
} else {
i = 0;
}
switch (i) {
case 0:
shapeArray.add(new Circle());
break;
case 1:
shapeArray.add( new Square());
break;
case 2:
shapeArray.add( new Star());
break;
case 3:
shapeArray.add(new Triangle());
break;
}
shapeArray.get(i).setX(e.getX());
shapeArray.get(i).setY(e.getY());
repaint();
animationTimer.start();
j += 1;
}
但是当我在paintComponent中调用我的draw方法时-
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(Color.BLACK);
shapeArray.get(i).draw(g, this);
// shapeArray.get(i).bounce(g, this);
}// end paintComponent
-我从 draw 方法的调用中得到错误。我在正确的轨道上吗?如何使用超类数组列表调用子类型的这个方法?
编辑: 抽象超类:
public abstract class Shapes {
Graphics g;
protected int width = 0;
protected int height = 0;
protected int x = 0;
protected int y = 0;
int d = 5;
int c = 5;
Random myRandom = new Random();
protected Color colorArray[] = {new Color(255,0,0),new Color(255,179,0),new Color(255,255,0),
new Color(7,225,0),new Color(0,127,225),new Color(205,0,255)};
protected Color color;
public Integer RandomNum(Integer x){
myRandom = new Random();
return myRandom.nextInt(x);
}
abstract public void draw(Graphics g, JPanel jp);
abstract public void bounce(Graphics g,JPanel jp);
public void setWidth(Integer width) {
this.width = width;
}
子类构造函数和draw方法:
public Circle() {
this.x = 0;
this.y = 0;
this.width = RandomNum(100);
this.height = width;
this.color = colorArray[RandomNum(6)];
}
public void draw(Graphics g, JPanel jp) {
Graphics2D g2d = (Graphics2D) g;
int radius = width;
Point2D center = new Point2D.Float((x + width / 2), (y + height / 2));
Point2D focus = new Point2D.Float(x - (radius * 0.6f), y
- (radius * 0.6f));
float[] dist = { 0.1f, 0.2f, 1.0f };
Color[] colors = { Color.WHITE,
color, color };
RadialGradientPaint p = new RadialGradientPaint(center, radius, focus,
dist, colors, CycleMethod.NO_CYCLE);
if (g2d != null) {
g2d.setPaint(p);
int r2 = radius / 2;
g2d.fillOval(x - r2, y - r2, radius, radius);
}
// g.setColor(colorArray[RandomNum(colorArray.length)]);
// g.fillOval(x, y, width, height);
}
【问题讨论】:
-
在超类中强制转换或定义方法。在这里(和大多数地方)你想在超类中定义它。对于多态性,您可以在子类中覆盖它。
-
我在超类中有一个抽象方法,在每个子类中都会被覆盖。我需要更改什么才能使用 arraylist 访问覆盖吗?
-
不应该有。只要其他类不是抽象的或任何东西。你能发布一个简短的 sn-p 大概的 Shape 类及其抽象的bounce() 和其他类的bounce() 吗?
-
还有draw()。那就是你所说的错误发生的地方。
-
完成。当我使用常规对象数组时,所有这些都有效,但现在我需要一次拥有多个形状,我认为 arraylist 是这样做的方法。但我无法让它工作。
标签: java arraylist polymorphism