interface graphics{
public abstract double getPerimeter();
public abstract double getArea();
}
public class GraphicsTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
pair a = new pair(1,2);
pair b = new pair(2,3);
pair c = new pair(3,3);
Triangle tri = new Triangle(a,b,c);
System.out.println(tri.getPerimeter());
System.out.println(tri.getArea());
a.x = 2;
System.out.println(tri.getPerimeter());//改变
System.out.println(tri.getArea());
Triangle tri1 = new Triangle(new pair(2,1),new pair(1,3),new pair(3,2));//比较好
System.out.println(tri1.getPerimeter());
System.out.println(tri1.getArea());
System.out.println(tri1.getPerimeter());
System.out.println(tri1.getArea());
}
}
class pair{//点对类
public int x;
public int y;
pair(int x,int y){
this.x = x;
this.y = y;
}
static double point_d(pair a, pair b) {
int l = Math.abs(a.x-b.x);
int w = Math.abs(a.y-b.y);
return Math.sqrt(l*l+w*w);
}
}
class Triangle implements graphics{
private pair first;
private pair second;
private pair third;
Triangle(pair first, pair second, pair third){
//this.first.x = first.x; ERROR!!!!!!!!!!!!!!!!!!!!!!!!!!!!,成员对象变量未创建,为null
this.first = first;
this.second = second;
this.third = third;
}
public double getPerimeter(){
return pair.point_d(first, second)+
pair.point_d(first, third) +
pair.point_d(second, third);
}
@Override
public double getArea() {
int xl = (first.x<second.x ? first.x : second.x)<third.x ?
(first.x<second.x ? first.x : second.x) : third.x;
int xr = (first.x>second.x ? first.x : second.x)>third.x ?
(first.x>second.x ? first.x : second.x) : third.x;
int yu = (first.y<second.y ? first.y : second.y)<third.y ?
(first.y<second.y ? first.y : second.y) : third.y;
int yd = (first.y>second.y ? first.y : second.y)>third.y ?
(first.y>second.y ? first.y : second.y) : third.y;
return (xr-xl)*(yd-yu) - Math.abs((first.x-second.x)*(first.y-second.y)*0.5)
- Math.abs((first.x-third.x)*(first.y-third.y)*0.5)
- Math.abs((third.x-second.x)*(third.y-second.y)*0.5);
}
}
类的成员变量是对象时,在构造函数中对其初始化未对其new空间引发的问题