天天看點

Java查詢個人資訊

每個員工都會有自己的檔案,主管可以檢視在職員工的檔案。使用 Java 建立一個員工實體類,然後通過構造方法建立一個名為“王潔”的員工,最後列印出員工檔案資訊。示例步驟如下。

(1) 建立 Person 類,在該類中定義個人基本資訊屬性,并定義一個帶有參數的構造方法,代碼如下:

  1. public class Person
  2. {
  3. private String name; //姓名
  4. private int age; //年齡
  5. private String sex; //性别
  6. private String birthday; //出生日期
  7. private String constellation; //星座
  8. public Person(String name,int age,String sex,String birthday,String constellation)
  9. {
  10. this.name=name;
  11. this.age=age;
  12. this.sex=sex;
  13. this.birthday=birthday;
  14. this.constellation=constellation;
  15. }
  16. public String intro()
  17. {
  18. return"姓名:"+name+"\n年齡:"+age+"\n性别:"+sex+"\n出生日期:"+birthday+"\n星痤:"+constellation;
  19. }
  20. }

在 Person 類中,首先聲明了 5 個修飾符為 private 的成員變量(屬性),然後定義了 Person 類的構造方法,該構造方法中需要傳遞 5 個參數,并将傳遞的這 5 個參數值賦給該類中的 5 個成員變量。接着建立了 intro() 方法,傳回個人基本資訊内容。

(2) 建立 PersonTest 類,并在該類中建立 main() 方法作為該程式的入口。在 main() 方法中使用 Person 類的構造方法對其屬性進行初始化,并調用 intro() 方法,輸出個人基本資訊。代碼如下:

  1. public class PersonTest
  2. {
  3. public static void main(String[] args)
  4. {
  5. Person person=new Person("王潔",21,"女","2016-02-21","獅子座");
  6. String intro=person.intro();
  7. System.out.println(intro);
  8. }
  9. }

在 TestPerson 類中調用了 Person 類的構造方法,并調用了 intro() 方法,進而完成了列印個人基本資訊的功能。運作 TestPerson 類,列印出的個人基本資訊如下:

姓名:王潔
年齡:21
性别:女
出生日期:2016-02-21
星痤:獅子座