这次尝试用两个类完成一个面积计算任务:
Point类代表平面上的点:
public class Point { private float x; private float y; public Point(float x,float y){ this.x=x; this.y=y; } public float getX() { return x; } public void setX(float x) { this.x = x; } public float getY() { return y; } public void setY(float y) { this.y = y; } }
TAngle这个类表示三个点控制的三角形
import com.ibm.Point; public class TAngle { private Point p1; private Point p2; private Point p3; public TAngle(Point p1,Point p2,Point p3){ this.p1=p1; this.p2=p2; this.p3=p3; } private double getLength(Point op1,Point op2){ float x=op1.getX()-op2.getX(); float y=op1.getY()-op2.getY(); double l=(double)x*x+y*y; return Math.sqrt(l); } private double getP(){ return (getLength(p1,p2)+getLength(p2,p3)+getLength(p3,p1))/2; } public double getArea(){ double p=getP(); double area=Math.sqrt(p*(p-getLength(p1,p2))*(p-getLength(p2,p3))*(p-getLength(p3,p1))); return area; } public static void main(String[] args){ Point p1=new Point(1,1); TAngle t=new TAngle(p1,new Point(5,1),new Point(3,4)); System.out.println("Triangle area="+t.getArea()); } }
两个类相互配合完成任务,对类的认识又更进一步。
本文转自张昺华-sky博客园博客,原文链接:http://www.cnblogs.com/xiandedanteng/p/3867223.html,如需转载请自行联系原作者