5.2
物件的成員
存取物件的成員
使用"."來存取物件的成員變數或成員函式,如:
class
Car
{
String licensePlate;
double speed;
double maxSpeed;
}
Car 有三個成員:
licensePlate
speed maxSpeed
如果 c 是 Car 的物件, 則 c 可以使用下列成員:
例如:
Car c = new Car();
c.licensePlate = "TK5897";
c.speed = 100;
c.maxSpeed = 220;
System.out.println(c.licensePlate + " 正以時速
" + c.speed + " 在前進中!");
使用Car物件類別的成員
class Car
{
String licensePlate;
double speed;
double maxSpeed;
}
class CarTest
{
public static void main(String args[])
{
Car c = new Car();
c.licensePlate = "TK5897";
c.speed = 100;
c.maxSpeed = 220;
System.out.println(c.licensePlate + " 正以時速
" + c.speed + " 在前進中!");
}
Car並沒有一個 main()可以執行. 它只在其它具有 main()
函式的程式執行時被產生、使用,然後被清除。
成員變數
vs. 區域變數
class Car
{
}
class ex
{
}
使用成員函式─方法(method)
類別是由一群屬性(成員變數)和方法(成員函式)所構成,物件則是由一群屬性值所構成,並且可以藉由成員函式來改變其屬性值。
class Car
{
String licensePlate; // e.g. "TK5897"
double speed; // 時速
double maxSpeed; // 最大時速
/*------ 成員函式 -----------------*/
void floorIt()
// 加速到最大
{
this.speed = this.maxSpeed;
} }
呼叫成員函式
class Car
{
String licensePlate;
double speed;
double maxSpeed; // 最大時速
void floorIt()
{
this.speed = this.maxSpeed; //加油至極速
}
}
class CarTest2
{
public static void main(String args[])
{
Car c = new Car();
c.licensePlate = "TK5897"; //
車牌號碼
c.speed =
0.0; //
時速
c.maxSpeed =
220; // 最大時速
System.out.println(c.licensePlate + " 正以時速 " +
c.speed + " 公里前進中.");
c.floorIt();
System.out.println(c.licensePlate + " 正以時速
" + c.speed + " 公里前進中.");
}
}
The output is:
TK5897 正以時速 0.0 公里前進中.
TK5897 正以時速 220 公里前進中
傳遞參數進入成員函式
物件導向設計準則:在物件外部,儘量不要直接存取成員變數值,應該經由成員函式。
傳遞參數範例:
void accelerate(double deltaV)
{
this.speed = this.speed + deltaV;
if (this.speed > this.maxSpeed) this.speed =
this.maxSpeed;
if (this.speed < 0.0) this.speed =
0.0;
}
Note : Java 傳遞參數的方式是傳值,而非傳參考(reference),更不是傳指標。
完整的範例:
class Car
{
String licensePlate; // e.g. "TK5897"
double speed; // 時速
double maxSpeed; // 最大時速
void floorIt() // 加速到最大
{
this.speed = this.maxSpeed;
}
void accelerate(double deltaV) //加速 deltaV
{
this.speed = this.speed + deltaV;
if (this.speed > this.maxSpeed) this.speed = this.maxSpeed;
if (this.speed < 0.0) this.speed = 0.0;
}
}
從成員函式傳回值
String getLicensePlate()
{
return this.licensePlate;
}
return this.licensePlated可改寫為return licensePlated
課堂練習:
設計一個含有main(
)函式的程式,使用上一節的Circle物件類別,測試個功能是否正確。
步驟一、建立一個Circle的物件
Circle c;
c = new
Circle;
步驟二、存取物件的資料
c.x=2.0;
c.y=2.0;
c.r=5.0;
步驟三、使用物件的功能
double a;
a = c.getArea(
);
步驟四、輸出面積
System.out.print("面積
= "+a);
步驟五、
改寫測試內容,先輸出圓心座標,再執行位移shift(10,-10),在輸出新的圓心座標。
|