void setup()
{
Fraction f= new Fraction(2, 7); //ประกาศ object f =new Fraction(2,7)ขึ้นมาเป็น Fraction
(ซึ่งเป็นคลาสที่สร้างไว้)เป็นตัวแปรแบบ local variable
Fraction g= new Fraction(16,8);
g.low(); //เป็นการเรียกใช้ method ภายในฟังชันโดยกำหนดobject
ที่ต้างการใช้ไว้ข้างหน้าmethod
text(g.toString(),50,50); //คำสั่งที่ใช้ในการแสดงข้อความบน Canvas
}
class Fraction //เป็นการสร้างClass ขึ้นมาเพื่อเก็บData & Method
ทำให้สะดวกในการใช้งานต่อไปในอนาคต
{
int n; //ประกาศ attribute n ขึ้นมาเป็นจำนวนเต้ม ซึ่งเป็นตัวแปรแบบlocal variable
แต่ตัวแปรนี้ method ภายในคลาสจะสามารถมองเห็นได้ด้วย
int d;
Fraction(int a, int b) //constructor ใช้ในการกำหนด object
{
this.n=a;
this.d=b;
}
Fraction() //constructor defult ไม่มี parameter
{
this.n=1;
this.d=1;
}
void add(int z) //method ที่ใช้ในการบวกเศษส่วนกับจำนวนเต็ม
{
this.n=(this.d*z)+this.n;
}
void add(Fraction k) //method ที่ใช้ในการบวกเศษส่วนกับเศษส่วน
เป็นการเขียนแบบ Overloading ชื่อmethod เหมือนกัน
แต่มีการรับ parameter ต่างกัน
{
this.n=(this.n*k.d)+(k.n*this.d);
this.d=this.d*k.d;
}
void mutiply(int z) //method ที่ใช้ในการคูณเศษส่วนกับจำนวนเต็ม
{
this.n=this.n*z;
}
void mutiply(Fraction k) //method ที่ใช้ในการคูณเศษส่วนกับเศษส่วน
{
this.n=this.n*k.n;
this.d=this.d*k.d;
}
void low() //method ที่ใช้ในการทำให้เป็นเศษส่วนอย่างต่ำ
{ int i=this.n;
while(i>0)
{
if(this.n%i==0 && this.d%i==0)
{
this.n=this.n/i;
this.d=this.d/i;
}
i--;
}
}
String toString()
{
fill(0);
return this.n+"/"+this.d; //return ค่ากลับไปยัง method
}
}
//อ้างอิงคำสั่งพื้นฐานต่างๆจาก lab1 http://com5630043.blogspot.com/search/label/lab1
//อ้างอิงอธิบายฟังก์ชันจาก lab2 http://com5630043.blogspot.com/search/label/lab2
//อ้างอิงอธิบายเรื่องif-elseจาก lab3 http://com5630043.blogspot.com/search/label/lab3%20%3A%20Condition
ไม่มีความคิดเห็น:
แสดงความคิดเห็น