类的成员变量是对象时,在构造函数中对其初始化未对其new空间引发的问题

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空间引发的问题

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值