import javax.swing.*;
import java.awt.*;
public abstract class Shape
{
public int x,y;
public Color c;
public Graphics g;
public abstract double area();
public abstract void draw(Graphics g);
public Shape()
{
}
public static void main(String[] args)
{
MyFrame frame = new MyFrame();
frame.setVisible(true);
}
public static class MyFrame extends JFrame
{
public static final String TITLE = "图形绘制";
public static final int WIDTH = 250;
public static final int HEIGHT = 300;
public MyFrame()
{
super();
setTitle(TITLE);
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
MyPanel panel = new MyPanel(this);
setContentPane(panel);
}
}
public static class MyPanel extends JPanel
{
private MyFrame frame;
public MyPanel(MyFrame frame)
{
super();
this.frame = frame;
}
@Override
public void paint(Graphics g)
{
super.paint(g);
Square s=new Square(20,40,80,80);
Rectangle r=new Rectangle(50,20,80,170);
Circle C=new Circle(70,20,8);
s.draw(g);
r.draw(g);
C.draw(g);
}
}
}
class Square extends Shape
{
public int x,y;
public int a,b;
public Square(int px,int py,int a,int b)
{
x=px;
y=py;
this.a=a;
this.b=b;
}
public double area()
{
return a*b;
}
public void draw(Graphics g)
{
g.setColor(Color.red);
g.drawRect(x,y,a,b);
}
}
class Rectangle extends Square
{
public int x,y;
public int a,b;
public Rectangle(int x,int y,int a,int b)
{
super(x,y,a,b);
//paint(g);
}
public double area()
{
return a*b;
}
public void draw(Graphics g)
{
super.draw(g);
}
}
class Circle extends Shape
{
public int r;
public int x,y;
public Circle(int r,int x,int y)
{
this.r=r;
this.x=x;
this.y=y;
//paint(g);
}
public double area()
{
return Math.PI*r*r;
}
public void draw(Graphics g)
{
g.setColor(Color.blue);
g.drawArc(x,y,r,r,0,360);
}
}
抽象类试验。
定义一组具有继承关系的类。Shape(形状)类是一个抽象类,包含 4
个数据成员(坐标 x,y,颜色 c,图形对象 g(Graphics 类对象)),一个构造方法和两
个抽象方法(求面积area()和draw方法) 。Square(正方形)由Shape派生,Rectangle
(矩形)由 Square 派生,Circle 由 Shape 派生。
对上述类进行测试。
请尝试按照利用坐标和颜色使用图形对象的方法进行图形对象的绘制和面积输出。
JAVA上机实验四