[实验任务一]:学号的单一
仿照课堂的身份证的例子,实现每个同学仅有一个学号这一问题。
1. 类图
1. 源代码
//StudentID.java
package test7;
public class StudentID {
private static StudentID instance = null;
private String id;
private StudentID(){}
public static StudentID getInstance() {
if (instance == null) {
System.out.println("学生信息注册,分配学号!");
instance = new StudentID();
instance.setStudentID("20224083");
} else {
System.out.println("学生信息已经被注册,获取其已经存在的学号!");
}
return instance;
}
private void setStudentID(String id) {
this.id = id;
}
public String getStudentID() {
return this.id;
}
}
//Client.java
package test7;
public class Client {
public static void main(String a[]) {
StudentID stu1,stu2;
String id1,id2;
System.out.println("第一次生成学生");
stu1 = StudentID.getInstance();
System.out.println("第二次生成学生");
stu2 = StudentID.getInstance();
System.out.println("两学生学号是否一致:" + (stu1==stu2));
id1 = stu1.getStudentID();
id2 = stu1.getStudentID();
System.out.println("第一次产生的学号:" + id1);
System.out.println("第二次产生的学号:" + id2);
System.out.println("内容是否相等:" + id1.equalsIgnoreCase(id2));
System.out.println("是否是相同对象:" + (id1==id2));
}
}
运行截图
标签:StudentID,学号,System,id,单例,println,单一,out From: https://www.cnblogs.com/po3a/p/18515008