A. Introduction

If you observe the triangle.java in 8.6 carefully, the repetition of x and y coordinates of each vertex almost makes you to ask: is it possible to include a Vertex or Point class as a member of the Triangle class?

private int Ax; private int Ay; private double ABlength; private int Bx; private int By; private double BClength; private int Cx; private int Cy; private double CAlength;

The answer is YES. Not only as instance members, but also as static members as necessary. This is called class inclusion, as shown below:

public class Point { double x; double y; public Point(){ //empty constructor } public Point(double i, double k){ //full constructor this.x = i; //use i & k because the formal parameters are general and hold no importance to code this.y = k; } public double getX(){ //getter or accessor return x; } public void setX(double i){ //setter or mutator x = i; } public double getY(){ //getter return y; } public void setY(double k){ //setter y = k; } public double distance (Point aPoint){ return Math.sqrt(Math.pow(this.x-aPoint.x,2)+Math.pow(this.y-aPoint.y,2)); } public String toStr(){ // it is NOT called by System.out.println() by default return "(" + x + ", " + y +")"; } public String toString(){ // it is called by System.out.println() by default return "(" + x + ", " + y +")"; } public boolean equals(Point p){ // to compare two Point objects return p.x==x&&p.y==y; } } class TriangleByVertex { Point a; Point b; Point c; public double perimeter() { return a.distance(b)+b.distance(c)+c.distance(a); } public double area() { double s = 0.5 * perimeter(); return Math.sqrt(s*(s-side(b,c))*(s-side(a, c))*(s-side(a, b))); } public double side(Point x, Point y){ return x.distance(y); } public double angle(Point x){ double cos; if(x.equals(a)) // use equals() method of Point class to check if two points are the same cos=(side(a,b)*side(a,b)+side(a,c)*side(a,c)-side(b,c)*side(b,c))/(2*side(a,b)*side(a,c)); else if(x.equals(b)) cos=(side(b,c)*side(b,c)+side(a,b)*side(a,b)-side(a,c)*side(a,c))/(2*side(b,c)*side(a,b)); else if(x.equals(c)) cos=(side(a,c)*side(a,c)+side(b,c)*side(b,c)-side(b,a)*side(b,a))/(2*side(a,c)*side(b,c)); else { System.out.println("This vertex does not below the triangle!"); return -1; } return Math.acos(cos); } }