1. 程式人生 > >JAVA第五週實驗(一).封裝一類三角形物件Triangle

JAVA第五週實驗(一).封裝一類三角形物件Triangle

實驗簡述:

1.封裝一類三角形物件Triangle,該類物件具有三條邊的屬性,具有初始化三角形的功能、修改邊長的功能、判斷三條邊能否構成三角形的功能、求周長的功能、求面積的功能。

測試函式原始碼:

public class test1 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Triangle Triangle1 = new Triangle(3f, 4f, 5f),Triangle2 = new Triangle(6f, 7f, 8f);
		System.out.println("Triangle1的邊長1是:"+Triangle1.get_length1());
		System.out.println("Triangle1的邊長2是:"+Triangle1.get_length2());
		System.out.println("Triangle1的邊長3是:"+Triangle1.get_length3());
		System.out.println("計算Triangle1的周長是:"+Triangle1.comgirth());
		System.out.println("計算Triangle1的面積是:"+Triangle1.comarea());
		
	    Triangle1.set_length1(4f);
	    float l = Triangle1.get_length1();
	    }

}


類的原始碼:

public class Triangle
	{
	float length1,length2,length3;//girth,area;
	Triangle(float x,float y,float z)
	{
		length1 = x;
		length2 = y;
		length3 = z;
	}
	void set_length1(float length1)
	{
		this.length1 = length1;
	}
	void set_length2(float length2)
	{
		this.length2 = length2;
	}
	void set_length3(float length3)
	{
		this.length3 = length3;
	}
	float get_length1()
	{
		return this.length1;
	}
	float get_length2()
	{
		return this.length2;
	}
	float get_length3()
	{
		return this.length3;
	}
   double comarea()
	{
		float p;
		double area;
		p = (length1 + length2 + length3)/2.0f;
		area = Math.sqrt(p*(p - length1)*(p - length2)*(p - length3));
		return area;
	}
	float comgirth()
	{
		float girth;
		girth = length1 + length2 + length3;
		return girth;
	}
	
	}
實驗總結:一個JAVA檔案只有一個public