创建一个学生类(id,name,sex,classNo,record),学生类中创建一个无参的构造方法,在构造方法中把自己的信息赋值给四个属性,record可以随机生成一个100之内的成绩,创建一个toString方法,方便完成学生信息的输出。请用构造方法实例化,静态工厂初始化、实例工厂初始化三种方式完成实例初始化。并测试输出(在测试方法中请提示测试的哪个方法测试方法,和相应的初始化的结果。如提示“构造方法实例化第一次,实例化内容:Student(学号:0001,name:张三 ,sex:女,classId:150704”,record:100)。
时间: 2023-03-24 09:04:55 浏览: 81
构造方法实例化第一次,实例化内容:Student(学号:0001,name:张三 ,sex:女,classId:150704,record:85)。
静态工厂初始化第一次,实例化内容:Student(学号:0002,name:李四 ,sex:男,classId:150705,record:72)。
实例工厂初始化第一次,实例化内容:Student(学号:0003,name:王五 ,sex:女,classId:150706,record:93)。
以下是代码实现:
```
public class Student {
private String id;
private String name;
private String sex;
private String classNo;
private int record;
public Student() {
this.id = "0001";
this.name = "张三";
this.sex = "女";
this.classNo = "150704";
this.record = (int) (Math.random() * 100);
}
public Student(String id, String name, String sex, String classNo, int record) {
this.id = id;
this.name = name;
this.sex = sex;
this.classNo = classNo;
this.record = record;
}
public static Student createStudentByStaticFactory() {
return new Student("0002", "李四", "男", "150705", (int) (Math.random() * 100));
}
public Student createStudentByInstanceFactory() {
return new Student("0003", "王五", "女", "150706", (int) (Math.random() * 100));
}
@Override
public String toString() {
return "Student(学号:" + id + ",name:" + name + ",sex:" + sex + ",classId:" + classNo + ",record:" + record + ")";
}
}
```
测试代码:
```
public class Test {
public static void main(String[] args) {
Student s1 = new Student();
System.out.println("构造方法实例化第一次,实例化内容:" + s1.toString());
Student s2 = Student.createStudentByStaticFactory();
System.out.println("静态工厂初始化第一次,实例化内容:" + s2.toString());
Student s3 = new Student().createStudentByInstanceFactory();
System.out.println("实例工厂初始化第一次,实例化内容:" + s3.toString());
}
}
```
阅读全文