主类中主要分为三步:
1.初始化数据
2.设置类的关联关系,关系绑定
3.取得数据
例子:
package *;
/*主类*/
public class App {
public static void main(String[] args) {
//第一步:初始化数据,实例化
BanJi bj=new BanJi("17计科","综合楼203");
BanZhang bz=new BanZhang("王宝宝","13105330001");
//第二步:设置关联关系,在这里实现一对一,一对多,多得多,设置对象间的具体关系
bj.setBanZhang(bz);
bz.setBanJi(bj);
//第三步:取得数据
//1、班级的班长 2、班长所在班级
System.out.println("班级->"+bj.getInfo());
String str=bj.getBanZhang().getInfo();
System.out.println(" 的班长->"+str);
System.out.println("班长->"+bz.getInfo());
System.out.println(" 所属班级->"+bz.getBanJi().getInfo());
}
}
子类
package *;
public class BanJi {
private String name;
private String loc;
private BanZhang banZhang;//需要绑定关系的对象,数据类型为对象名称
//成员变量
public BanJi() {}
public BanJi(String name, String loc) {
this.name = name;
this.loc = loc;
}
//构造方法,初始化
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
public BanZhang getBanZhang() {
return banZhang;
}
public void setBanZhang(BanZhang banZhang) {
this.banZhang = banZhang;
}
//getter,setter方法获取私有属性
public String getInfo() {
return "班级名称:" + this.name + ",地址" + this.loc;
}
}
package *;
public class BanZhang {
private String name;
private String phoneNo;
private BanJi banJi;//需要绑定关系的对象,数据类型为对象名称
//成员变量
public BanZhang(){}
public BanZhang(String name, String phoneNo) {
this.name = name;
this.phoneNo = phoneNo;
}
//构造方法,初始化
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public BanJi getBanJi() {
return banJi;
}
public void setBanJi(BanJi banJi) {
this.banJi = banJi;
}
//getter,setter方法获取私有属性
public String getInfo(){
return "班长姓名:"+this.name+",联系电话:"+this.phoneNo;
}
}
结果