编程计算三角形的面积和周长。要求如下:
(1)、设计一个接口InterfaceShape,其中有计算三角形的面积和周长的抽象方法;
(2)、设计一个点类Point,其中有必要的构造方法和一般的访问器方法(getXXX())和修改器方法(setXXX());
(3)、通过实现InterfaceShape接口类的方式,并使用Point类,设计三角形Triangle类,其中有必要的构造方法和计算三角形的面积和周长的方法;
(4)、设计一个主类Shape,对使用Point类,设计三角形Triangle类进行测试,计算三角形的面积和周长,并在屏幕上输出。
知识点:综合,面向对象编程
InterfaceShape 接口:
public interface InterfaceShape
{
public abstract double getArea();
public abstract double getFerence();
}
Point 类:
public class Point
{
double x;
double y;
public Point(double x, double y)
{
this.x = x;
this.y = y;
}
public double getX()
{
return x;
}
public void setX(double x)
{
this.x = x;
}
public double getY()
{
return y;
}
public void setY(double y)
{
this.y = y;
}
}
Triangle 类:
public class Triangle implements InterfaceShape
{
Point a;
Point b;
Point c;
public double s1;
public double s2;
public double s3;
public Triangle(Point A, Point B, Point C)
{
this.a = A;
this.b = B;
this.c = C;
}
//三角形面积
public double getArea()
{
double p=(this.getS1()+this.getS2()+this.getS3())/2;
return Math.pow(p*(p-this.getS1())*(p-this.getS2())*(p-this.getS3()),0.5);
}
//三角形周长
public double getFerence()
{
return this.getS1()+this.getS2()+this.getS3();
}
public double getS1()
{
return Math.sqrt(Math.pow(a.getX()-b.getX(),2)+Math.pow(a.getY()-b.getY(), 2));
}
public double getS2()
{
return Math.sqrt(Math.pow(a.getX()-c.getX(),2)+Math.pow(a.getY()-c.getY(), 2));
}
public double getS3()
{
return Math.sqrt(Math.pow(b.getX()-c.getX(),2)+Math.pow(b.getY()-c.getY(), 2));
}
}
Shape 测试类:
public class Shape
{
public static void main(String[] args)
{
Point a=new Point(0,0);
Point b=new Point(3,0);
Point c=new Point(0,4);
Triangle tri = new Triangle(a,b,c);
System.out.println("三角形面积:"+tri.getArea());
System.out.println("三角形周长:"+tri.getFerence());
}