我用的是接口与抽象类共同使用的方法:
接口:
package zz;
interface Shapes{
double getArea();
double getPerimeter();
}
接口抽象类:
package zz;
public abstract class AbShapes implements Shapes{
protected int x,y,k;
protected double m;
public AbShapes(int x1,int y1,int k1,double m1){
x=x1;y=y1;k=k1;m=m1;
}
}
主函数类(利用接口引用实现类运行时重载):
package zz;
import java.applet.Applet;
import java.awt.Graphics;
class Rect extends AbShapes{
public Rect(int x1, int y1, int width, double height) {
super(x1, y1, width, height);
// TODO Auto-generated constructor stub
}
@Override
public double getArea() {
// TODO Auto-generated method stub
return (k*m);
}
@Override
public double getPerimeter() {
// TODO Auto-generated method stub
return (2*k+2*m);
}
}
class Triangle extends AbShapes{
public Triangle(int x1, int y1, int z1) {
super(x1, y1, z1, (x1+y1+z1)/2.0);
// TODO Auto-generated constructor stub
}
@Override
public double getArea() {
// TODO Auto-generated method stub
return Math.sqrt(m*(m-k)*(m-x)*(m-y));
}
@Override
public double getPerimeter() {
// TODO Auto-generated method stub
return (k+x+y);
}
}
class Circle extends AbShapes{
public Circle(int x, int y, int width) {
super(x, y, width, width/2.0);
// TODO Auto-generated constructor stub
}
@Override
public double getArea() {
// TODO Auto-generated method stub
return m*m*Math.PI;
}
@Override
public double getPerimeter() {
// TODO Auto-generated method stub
return (2*Math.PI*m);
}
}
public class Run extends Applet{
Rect rect=new Rect(5,15,25,25);
Triangle triangle=new Triangle(5,5,8);
Circle cir=new Circle(13,90,25);
public double reArea(Shapes m) {
return m.getArea();
}
public double rePerimeter(Shapes m) {
return m.getPerimeter();
}
public void paint(Graphics g) {
Rect rect=new Rect(5,15,25,25);
Triangle tri=new Triangle(5,5,8);
Circle cir=new Circle(13,90,25);
g.drawRect(rect.x, rect.y, rect.k, (int)rect.m);
g.drawString("Rect Area:"+reArea(rect), 50, 35);
g.drawString("Rect Perimeter:"+rePerimeter(rect), 50, 55);
g.drawString("Triangle Area:"+reArea(tri), 50, 75);
g.drawString("Triangle Perimeter:"+rePerimeter(tri), 50, 95);
g.drawOval(cir.x-(int)cir.k/2,cir.y-(int)cir.k/2,cir.k,cir.k);
g.drawString("Circle Area:"+reArea(cir),50,115);
g.drawString("Circle Perimeter:"+rePerimeter(cir),50,135);
}
}