封装学生关联demo01

package com.com.FZAL;

public class test {
public static void main(String[] args) {
//new对象
Studentf s0 = new Studentf("松松","173","男",23);
ZY t0 = new ZY("机械工程","001",4);


//设置学生所学专业
s0.setZnames(t0);
//修改学生所学专业
ZY t1 = new ZY("材料","002",24);
s0.setZnames(t1);
//自我介绍
String s = s0.introduce();
System.out.println(s);
System.out.println(s0.getZnames().getZid());

}
}
package com.com.FZAL;

public class Studentf {
private String sname;
private String sid;
private String sex;
private int age;
private ZY znames;

public ZY getZnames() {
return znames;
}

public void setZnames(ZY znames) {
this.znames = znames;
}

public Studentf() {
}

public Studentf(String sname, String sid, String sex, int age) {
this.sname = sname;
this.sid = sid;
this.sex = sex;
this.age = age;
}

public String getSname() {
return sname;
}

public void setSname(String sname) {
this.sname = sname;
}

public String getSid() {
return sid;
}

public void setSid(String sid) {
this.sid = sid;
}

public String getSex() {
return sex;
}

public void setSex(String sex) {
this.sex = sex;
}

public int getAge() {
return age;
}

public void setAge(int age) {
if (age < 0 || age > 100){
System.out.println("sb");
return;
}
this.age = age;
}
//没有设置专业 指针异常解决
public String introduce(){
ZY sub = this.znames;
String s = "学生的信息如下:" + "姓名" + this.getSname() +
"\n年龄" + this.getAge() +
"\n学号" + this.getSid() +
"\n性别" + this.getSex() +
"\n专业名字" + (sub==null?"null":sub.getZname()) +
"\n专业编号" + (sub==null?"null":sub.getZid()) +
"\n专业年限" + (sub==null?"null":sub.getZage())
;
return s;
}
}
package com.com.FZAL;

public class ZY {
private String zname;
private String zid;
private int zage;

public ZY() {
}

public ZY(String zname, String zid, int zage) {
this.zname = zname;
this.zid = zid;
this.zage = zage;
}

public String getZname() {
return zname;
}

public void setZname(String zname) {
this.zname = zname;
}

public String getZid() {
return zid;
}

public void setZid(String zid) {
this.zid = zid;
}

public int getZage() {
return zage;
}

public void setZage(int zage) {
this.zage = zage;
}
public String introduceZ(){
String t = "专业信息如下" + "专业名称" + this.getZname()+
"\n编号" + this.getZid() +
"\n年限" + this.getZage();
return t;
}
}

posted @ 2022-05-21 15:13  小松2739  阅读(17)  评论(0编辑  收藏  举报