Java中一對多映射關係

來源:互聯網
上載者:User

標籤:title   個人   測試   src   運行   double   nbsp   方法   str   

通過例子,一個人可以有多輛汽車

定義人   這個類

人可以有很多輛汽車,類中車屬性用數組

class Person{     private String name;    private String phone;    private Car[] car;     public Person() {}    public Person(String name, String phone) {        this.name = name;        this.phone = phone;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getPhone() {        return phone;    }    public void setPhone(String phone) {        this.phone = phone;    }    public Car[] getCar() {        return car;    }    public void setCar(Car[] car) {        this.car = car;    }    public String getInfo(){        return "姓名"+name+",電話"+phone;    }}

然後定義汽車  這個類

class Car{     private String name;    private double price;    private Person person;    public Car() {}    public Car(String name,double price) {        this.name = name;        this.price = price;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public double getPrice() {        return price;    }    public void setPrice(double price) {        this.price = price;    }    public Person getPerson() {        return person;    }    public void setPerson(Person person) {        this.person = person;    }    public String getInfo() {        return "品牌:"+name+" 價格:"+price;    }

之後,在測試類別中,分別執行個體Person類和Car類

人這個對象只new一個

汽車可以無限個,這裡象徵性執行個體三個

        Person p = new Person("阿三","33333333");        Car c1 = new Car("寶馬",400000);        Car c2 = new Car("寶來",100000);        Car c3 = new Car("寶駿",800

對象執行個體化之後,設定彼此的關係,即一個人對應三台車,每台車都對應一個人

通過set方法傳值

        p.setCar(new Car[]{c1,c2,c3});         c1.setPerson(p);        c2.setPerson(p);        c3.setPerson(p);

測試

通過人,查詢其下的車輛資訊

System.out.println(p.getInfo()+"擁有的車輛");for(int i=0;i<p.getCar().length;i++) {    System.out.println(p.getCar()[i].getInfo()); //數群組類型用for迴圈列印}

運行

通過車,尋找所屬人資訊

System.out.println(c1.getInfo()+" 這輛車的所屬人:"+c1.getPerson().getInfo());System.out.println(c2.getInfo()+" 這輛車的所屬人:"+c1.getPerson().getInfo());System.out.println(c3.getInfo()+" 這輛車的所屬人:"+c1.getPerson().getInfo());

運行

 

Java中一對多映射關係(轉)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.