1、要求可以通过一个城市找找到它所对应的省份信息;
2、可以通过一个省份找到所有城市的信息
第一步:先写基本字段
class Province {
private int pid;
private String pname;
//setter, getter 和 无参构造省略
public Province(int pid , String pname) {
this.pid = pid;
this.pname = pname;
}
public void getInfo() {
return "省份编号:" + this.pid + ", 省份名称:" + this.pname;
}
}
class City {
private int cid;
private String cname;
//setter, getter 和 无参构造省略
public City(int cid , String cname) {
this.cid = cid;
this.cname = cname;
}
public void getInfo() {
return "城市编号:" + this.cid + ", 城市名称:" + this.cname;
}
}
第二步:设置关键字段(引用)
class Province {
private int pid;
private String pname;
private City[] cities;
//setter, getter 和 无参构造省略
public Province(int pid , String pname) {
this.pid = pid;
this.pname = pname;
}
public void setCity(City[] cities){
this.cities = cities;
}
public City[] getCity() {
return this.cities;
}
public void getInfo() {
return "省份编号:" + this.pid + ", 省份名称:" + this.pname;
}
}
class City {
private int cid;
private String cname;
private Province province;
//setter, getter 和 无参构造省略
public City(int cid , String cname) {
this.cid = cid;
this.cname = cname;
}
public void setProvince(Province province) {
this.province = province;
}
public Province getProvince() {
return this.province;
}
public void getInfo() {
return "城市编号:" + this.cid + ", 城市名称:" + this.cname;
}
}
第三步:代码数据测试
public class Province_City {
public static void main(String[] args) {
//第一步:设置数据
//1. 先准备好各自独立的对象
Province p = new Province(1 , "江苏");
City c1 = new City(2001 , "南京");
City c2 = new City(2002 , "南通");
City c3 = new City(2003 , "无锡");
//2. 设置关系
c1.setProvince(p); //一个城市属于一个省份
c2.setProvince(p);
c3.setProvince(p);
p.setCities(new City[]{c1 , c2 , c3}); //一个省份有多个城市
//第二步:取出数据
System.out.println(c1.getProvince().getInfo());
for (int x=0; x < p.getCities().length ; x++) {
System.out.println("\t|- " + p.getCities()[x].getInfo());
}
}
}
网友评论