如何将这两个类链接在一起,以显示Person和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的字段和方法名称
  • 常数与CCD_ 8

最新更新