import java.util.Vector;
abstract class GraphicObject {
int x, y, w, h;
GraphicObject(int x, int y, int w, int h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
public abstract void view();
}
class Rect extends GraphicObject {
Rect(int x, int y, int w, int h) {
super(x, y, w, h);
// TODO Auto-generated constructor stub
}
public void view() {
// TODO Auto-generated method stub
System.out.println("this rectangle is " + x + "," + y + " -> " + w + "," + h);
}
}
class Line extends GraphicObject { // make here
Line(int x, int y, int w, int h) {
super(x, y, w, h);
// TODO Auto-generated constructor stub
}
@Override
public void view() { // make here
// TODO Auto-generated method stub
System.out.println("this line is " + x + "," + y + " -> " + w + "," + h);
}
}
public class GraphicEditor {
Vector<GraphicObject> v = new Vector<GraphicObject>();
void add(GraphicObject ob) // edit here
{
v.add(ob);
}
void draw() {
for (int i = 0; i < v.size(); i++) {
v.get(i).view();
}
}
public static void main(String[] args) {
GraphicEditor g = new GraphicEditor();
g.add(new Rect(2, 2, 3, 4));
g.add(new Line(3, 3, 8, 8));
g.add(new Line(2, 5, 6, 6));
g.draw();
}
}
为了执行main()函数,应创建继承GraphicObject的Rect和Line,并应编写GraphicEditor类所需的add()和draw()方法。
我是编程的初学者,有很多方法可以解决此问题,所以我选择了此方法。
我解决了问题,但我认为会有更好的方法。
我发布此信息是为了纠正语法上不干净或不正确的部分。
请指出我的代码中的错误部分。
您的代码确定。但有一些建议:
Collection
,List
和...而不是Vector
(Why is Java Vector (and Stack) class considered obsolete or deprecated?)foreach
或Java 8 streams
代替for
循环获得更清晰的代码。