建立people資料類別,成員變數Name(姓名):String、age(年齡):integer、email(電子信箱):String的私人變 數,除了提供設定姓名、年齡、電子信箱方法外,再加上取得姓名、年齡、電子信箱方法,並設計一個能進行初值設定的建構子。最後建立PrintPeople()方法 顯示資料。
=================程式內容=================
public class ChB { public static void main(String[] args) { people p1 = new people();//沒設定資料進去 p1.printPeople();//印出來的是建構子裡面預設的資料 people p2 = new people("宅女BB",18,"[email protected]"); p2.printPeople(); } } class people//people資料類別 { private String name;//名字宣告為字串 private int age;//年齡宣告為整數 private String email;//E-mail宣告成字串 public people()//這就是所謂的建構子,跟類別名稱people相同 { this("宅男AA",18,"[email protected]");//使用this設定初始資料內容 } public people(String name, int age, String email) {//使用this設定使用者資料訥容(this寫法有兩種) this.name = name; this.age = age; this.email = email; } public void printPeople() {//印出的方法 System.out.println("姓名:"+name); System.out.println("年齡:"+age); System.out.println("E-mail:"+email); } }
=============執行後結果範例=============
姓名:宅男AA
年齡:18
E-mail:[email protected]
姓名:宅女BB
年齡:18
E-mail:[email protected]
Finished executing
有不懂的地方or怪怪的地方幫忙回應討論一下唷︿︿”