5.3
建構者(Constructors)
建構者函式(Constructors)
- 建構者函式名稱與類別名稱一樣。
- 建構者函式的最重要目的是對物件的屬性進行初值化的工作。
- 建構者函式不能傳回值,但可以傳入參數值。
- 一個類別可以擁有多個建構者函式,但每個建構者函式傳入的參數必須不同。
例:
Car() //不傳入任何參數
{
this.licensePlate = ""; //
this.speed = 0.0; // 建立一個新物件時,物件屬性的預設值
this.maxSpeed = 200.0; //
}
Car(String licensePlate, double speed, double maxSpeed) //傳入三個參數
{
this.licensePlate = licensePlate; //
this.speed = speed; // 使用傳入的三個參數值作初值化
this.maxSpeed = maxSpeed; //
}
Car(String licensePlate, double maxSpeed) //只傳入兩個參數
{
this.licensePlate = licensePlate; //使用傳入的兩個參數值作初值化
this.speed = 0.0; // ,另一個speed則預設為0.0
this.maxSpeed = maxSpeed; //
}
使用建構者函式範例程式
class CarTest4
{
public static void main(String args[])
{
Car c = new Car("New York A45 636", 123.45);
System.out.println(c.getLicensePlate() + " is moving at " + c.getSpeed() + " km/hr.");
for (int i = 0; i < 15; i++)
{
c.accelerate(10.0);
System.out.println(c.getLicensePlate() + " is moving at " + c.getSpeed() + " km/hr");
}
}
}
課堂練習:
將下列程式將入不同的建構者函式:
public class
Circle
{
public double x,y;
public double r;
public double getCirCumf( )
{
return 2*3.14159*r;
}
public double getArea( )
{
return 3.14159*r*r;
}
}
建構者函式傳遞參數分別為:
1.
只傳入圓心;
2.
只傳入半徑;
3.
傳入圓心和半徑;
|