Java程式設計基礎 物件導向 練習 靜態Factory 方法

來源:互聯網
上載者:User

標籤:運行   str   err   資訊   next   測試   靜態Factory 方法   rgs   定義   

  定義靜態域nextId和一個靜態方法getNextId,將三個Employee對象寫入數組,然後列印僱員資訊。最後列印出寫一個可用的員工標識碼來展示靜態方法。

package company;public class Gettext {    public static void main(String[] args) {        // TODO 自動產生的方法存根        Employee[] staff = new Employee[3];        staff[0] = new Employee("Tom",40000);        staff[1] = new Employee("Dick",60000);        staff[2] = new Employee("Harry",65000);        for(Employee e:staff)        {            e.setId();            System.out.println("name= " + e.getName() + " id= " + e.getId() + " salary=" + e.getSalary());        }        int n = Employee.getNextId();        System.out.println("Next available id = " + n);    }}
package company;public class Employee {    private static int nextId = 1;    private String name;    private double salary;    private int id;    public Employee(String name,double salary)    {        this.name = name;        this.salary = salary;        id = 0;    }    public String getName()    {        return name;    }    public double getSalary()    {        return salary;    }    public int getId()    {        return id;    }    public void setId()    {        id = nextId;        nextId++;    }    public static int getNextId()    {        return nextId;    }    public static void main(String[] args) {   //用於獨立測試Employee類        // TODO 自動產生的方法存根        Employee e = new Employee("Herry",50000);        System.out.println(e.getName() + "  " + e.getSalary());    }}

  程式運行結果:

  name= Tom id= 1 salary=40000.0
  name= Dick id= 2 salary=60000.0
  name= Harry id= 3 salary=65000.0
  Next available id = 4

Java程式設計基礎 物件導向 練習 靜態Factory 方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.