簡體   English   中英

我如何將這兩個類鏈接在一起以顯示 Person 和 Address 之間的一對多關系

[英]How would I link the two classes together to show the one to many relationship between Person and Address

地址類:

public class Address {

    private String country;
    private String county;
    private String city;
    private String postcode;
    private String HouseNumber;

    public Address(String country, String county, String city, String postcode, String HouseNumber) {
        this.country = country;
        this.county = county;
        this.city = city;
        this.postcode = postcode;
        this.HouseNumber = HouseNumber;
    }

    public void view_adress() {
        String[] address = {country, county, city, postcode, HouseNumber};
        
        for (int i = 0; i<address.length; i++) {
            System.out.println(address[i]);
        }
    }
                
    public void viewHouseNumber() {
        System.out.print(HouseNumber);
    }
}

人物類:

public class Person {
    private String firstName;
    private String lastName;
    private String Date_of_birth;
    private String PhoneNumber;
    private String[] address;
    
    public Person (String firstName, String lastName, String Date_of_birth, String PhoneNumber, String[] address) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.Date_of_birth = Date_of_birth;
        this.PhoneNumber = PhoneNumber;
        this.address = address;
    }

    public void view_PhoneNumber() {
        System.out.print(PhoneNumber);
    }
}

使用 OOP組合

public class Person {
    //...
    List<Address> addresses;
    //...
}

Person一個實例將具有 0 個或多個Address實例。

請注意,在實際場景中,您最好還希望在Address類中保留一系列userId ,因為多個用戶可能擁有一個或多個地址,這意味着,那你的關系必須是Many-To-Many

同樣(完全)重要的是堅持Java 命名約定和名稱:

  • 使用PascalCase類;
  • 字段和方法名稱使用camelCase命名法;
  • ALL_CAPS_SEPARATED_WITH_UNDERSCORES常量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM