设计一个接口Shape,包括2个抽象方法getPerimeter()和getArea(),分别是计算形状的周长和面积。设计实现该接口的具体类Rectangle、Triangle和Circle,分别表示矩形、三角形和圆,在三个子类中建立各自的构造方法并重写getPerimeter()和getArea()。在main()中声明Shape变量s,利用s输出某矩形、三角形和圆的周长和面积。
创建TextShape类:
代码:
interface shape
{
public abstract void getPerimeter();
public abstract void getArea();
}
class Rectangle implements shape{
int a;
int b;
public Rectangle(int a,int b)
{
this.a = a;
this.b = b;
}
public void getArea()
{
System.out.println(“矩形面积为:”+a*b);
}
public void getPerimeter()
{
System.out.println(“矩形周长为:”+2*(a+b));
}
}
class Triangle implements shape
{
int x;
int y;
int z;
public Triangle (int x,int y,int z)
{
this.x = x;
this.y = y;
this.z = z;
}
public void getArea()
{
System.out.println(“三角形的周长是:”+(x+y+z));
}
public void getPerimeter()
{
double p=(x+y+z)/2;
System.out.println(“三角形的面积是:”+Math.sqrt(p*(p-x)*(p-y)*(p-z)));
}
}
class Circle implements shape
{
int r;
public Circle(int r)
{
this.r = r;
}
public void getArea()
{
System.out.println(“圆面积为:”+Math.PI*r*r);
}
public void getPerimeter()
{
System.out.println(“圆周长为:”+2*Math.PI*r);
}
}
public class TextShape {
public static void main(String[] args)
{
shape r = new Rectangle(6,8);
r.getArea();
r.getPerimeter();
shape t = new Triangle(3,4,5);
t.getArea();
t.getPerimeter();
shape c = new Circle(6);
c.getArea();
c.getPerimeter();
}
}