標題:
建構子 (一)
[打印本頁]
作者:
tonyh
時間:
2017-4-15 10:24
標題:
建構子 (一)
本帖最後由 tonyh 於 2017-4-15 11:44 編輯
建構子, 又稱建構函式或建構方法, 是一種特殊的函式.
透過建構子, 在自類別生成實體物件的同時, 能對物件進行 "初始化".
public class Ch57 //主類別
{
public static void main(String args[])
{
Car bus=new Car("公車",6,40);
Car truck=new Car("卡車",8,3);
Car taxi=new Car("計程車",4,5);
bus.showInfo();
truck.showInfo();
taxi.showInfo();
}
}
class Car //定義類別
{
String name;
int wheel,load;
Car(String n,int w,int l) //定義建構子
{
name=n;
wheel=w;
load=l;
}
void showInfo()
{
System.out.println(name+"有"+wheel+"個輪子,可載"+load+"人.");
}
}
複製代碼
作者:
黃茂勛
時間:
2017-4-15 11:42
public class Ch58
{
public static void main(String args[])
{
Car bus=new Car("公車",4,20);
Car truck=new Car("卡車",8,3);
Car taxi=new Car("計程車",4,5);
bus.showInfo();
truck.showInfo();
taxi.showInfo();
}
}
class Car
{
String name;
int wheel,load;
Car(String n,int w,int l)
{
name=n;
wheel=w;
load=l;
}void showInfo()
{
System.out.println(name+"有"+wheel+"個輪子,可載"+load+"人.");
}
}
複製代碼
作者:
陳泓瑜
時間:
2017-4-15 11:43
public class Ch46
{
public static void main(String args[])
{
Car bus=new Car("公車",6,40);
Car truck=new Car("卡車",8,3);
Car taxi=new Car("計程車",4,5);
bus.showInfo();
truck.showInfo();
taxi.showInfo();
}
}
class Car
{
String name;
int wheel;
int load;
Car(String n,int w,int l)
{
name=n;
wheel=w;
load=l;
}
void showInfo()
{
System.out.println(name+"有"+wheel+"個輪子,可載"+load+"人。");
}
}
複製代碼
作者:
陸長辰
時間:
2017-4-15 11:46
import java.util.Scanner;
public class Ch50
{
public static void main(String args[])
{
Car bus=new Car("公車",4,20);
Car truck=new Car("卡車",4,20);
Car taxi=new Car("計程車",4,20);
bus.showInfo();
truck.showInfo();
taxi.showInfo();
}
}
class Car
{
String name;
int wheel,load;
Car (String n,int w,int l)
{
name=n;
wheel=w;
load=l;
}void showInfo()
{
System.out.println(name+"有"+wheel+"個輪子可載"+load+"人");
}
}
複製代碼
歡迎光臨 種子論壇 | 高雄市資訊培育協會學員討論區 (http://seed.istak.org.tw/)
Powered by Discuz! 7.2