package com.imooc; public class TempWork { public static void main(String[] args) { //创建学科类的对象 Subject sb = new Subject("J0001","计算机科学与应用",4); System.out.println("专业信息如下:"); System.out.println(sb.getInFo()); System.out.println("==================="); //创建学生类的对象 Student stu1 = new Student("张三",01,'男',29,sb); Student stu2 = new Student("李四",02,'男',28); Student stu3 = new Student("王五",03,'女',27); System.out.println("学生信息如下:"); System.out.println(stu1.print()); } } /** * 建立一个学科类Subject,属性有专业编号,专业名称,学制年限 * @author idea * */ class Subject{ private String num; private String sbname; private int years; //定义无参构造 public Subject(){} //定义三参构造 public Subject(String num,String sbname,int years){ this.setNum(num);//专业编号 this.setSbname(sbname);//专业名称 this.setYears(years);//学制年限 } public void setNum(String num) { this.num = num; } public void setSbname(String sbname) { this.sbname = sbname; } public void setYears(int years) { this.years = years; } public String getNum() { return num; } public String getSbname() { return sbname; } public int getYears() { return years; } //定义一个输出学科信息的方法 public String getInFo(){ return "专业编号:"+this.num+"\n" +"专业名称:"+this.sbname+"\n" +"学制年限:"+this.years+"年"; } } /** * 建立一个学生类Student,属性有姓名,学号,性别,年龄,所报专业名称,学制年限 */ class Student{ private String stuname;//学生姓名 private int id;//学号 private char sex;//性别 private int age;//年龄 private Subject studentSubject;//将学生所报专业的专业信息作为学生的一个属性 //定义无参构造 //定义一个四参构造 public Student(String stuname,int id,char sex,int age){ this.setStuname(stuname); this.setId(id); this.setSex(sex); this.setAge(age); } //定义五参构造 public Student(String stuname,int id,char sex,int age,Subject studentSubject){ this.setStuname(stuname); this.setId(id); this.setSex(sex); this.setAge(age); this.setStudentSubject(studentSubject); } public void setStuname(String stuname) { this.stuname = stuname; } public void setId(int id) { this.id = id; } public void setSex(char sex) { this.sex = sex; } public void setAge(int age) { this.age = age; } public void setStudentSubject(Subject student) { this.studentSubject = studentSubject; } public String getStuname() { return stuname; } public int getId() { return id; } public char getSex() { return sex; } public int getAge() { return age; } public Subject getSutdentSubject() { //如果没有实例化则实例化,防止调用该方法时出现空指针异常 if(this.studentSubject==null){ this.studentSubject=new Subject(); } return studentSubject; } //定义一个输出学生信息的方法 public String print(){ return "学生姓名:"+this.getStuname()+"\n" +"学号:"+this.getId()+"\n" +"性别:"+this.getSex()+"\n" +"年龄:"+this.getAge()+"\n" +"所学专业编号:"+this.getSutdentSubject().getNum()+"\n" +"所报专业名称:"+this.getSutdentSubject().getSbname()+"\n" +"学制年限:"+this.getSutdentSubject().getYears(); } }
人贩
相关分类